2012-04-04 52 views
0

我有一個C結構約17個成員struct settings currentProfile並希望將其初始化爲零。 (我都與尤伯杯正確結構的語法和用typedef語法嘗試這樣)初始化C結構預期的表達式

所有成員設置爲零,我用currentProfile = {0}

在此行的編譯器給人的埃羅Expected an expression

上午我正確初始化? 謝謝

+2

請出示一些代碼,展品錯誤。 – 2012-04-04 10:01:07

+0

這個概念在K n R書中明確提到 – 2012-04-04 10:31:01

+0

@MichaelFoukarakis ''設置currentProfile,newProfile void initProfile(void){ currentProfile = {0}; }'' – Toby 2012-04-04 10:47:25

回答

6

您正在做一個(無效)賦值而不是初始化。

要初始化結構對象與所有成員設置爲0

struct settings currentProfile = {0}; 

要其聲明之後的結構對象的所有成員設置爲0

memset(&currentProfile, 0, sizeof currentProfile); 
+1

請注意,在memset操作之前動態分配的指向成員可能需要'free'd以避免內存泄漏。 – moooeeeep 2012-04-04 10:08:19

+0

@moooeeeep,在初始化時不是問題! – Shahbaz 2012-04-04 10:09:13

+0

@Shahbaz但稍後可能會成爲問題。 – moooeeeep 2012-04-04 10:10:17

1

memset(pointer_to_struct,0,size_of_struct);

#include <string.h> 

struct settings currentProfile; 
memset(&currentProfile, 0, sizeof(struct settings)); 
+0

我做了同樣的事情,但我得到一個錯誤,找到下面的代碼。 #include #include using namespace std; struct abc {int x; int y;}; struct abc xyz; int main(){ memset(&xyz,1,sizeof(struct xyz)); cout << xyz.x; //給垃圾 返回0;} – 2012-04-04 10:37:37

+0

您聲明「我有一個C結構...」。你的代碼是C++。 – jacekmigacz 2012-04-04 10:47:37

+0

查找C代碼#include #include // using namespace std; struct abc {int x; int y;}; struct abc xyz; int main(){ memset(&xyz,1,sizeof(struct abc)); // memset(&xyz,1,sizeof(struct xyz)); //給'sizeof'的錯誤無效應用爲不完整類型'struct xyz' printf(「xyz.x =%d」,xyz.x); //給垃圾 返回0;} – 2012-04-04 10:58:02