2012-04-04 9 views
0

私は約17人のメンバーがあるstruct settings currentProfileのC構造体を持っており、すべてのメンバーをゼロに初期化したいと思います。私は、コンパイラがExpected an expressionInitializing C structは式を期待しています

がアイ・アムERROを与え、このラインでcurrentProfile = {0}

を使用ゼロにすべてのメンバーを設定するには

を(私はユーバー-正しい構造体の構文でとtypedefの構文で両方これを試してみました)正しく初期化する? ありがとう

+2

その展示いくつかのコードを表示してくださいエラー。 –

+0

このコンセプトはK n R bookに明記されています –

+0

@MichaelFoukarakis '' settings currentProfile、newProfile void initProfile(void){ currentProfile = {0}; } '' – Toby

答えて

6

初期化ではなく、(無効な)割り当てを行っています。すべてのメンバーとあなたのStructオブジェクトを初期化する

0に設定:

struct settings currentProfile = {0}; 

を宣言した後、0に構造体オブジェクトのすべてのメンバーを設定するには:

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

注指摘-ようになったメンバーメモリリークを避けるために、 '' memset'操作の前にfree'dする必要があるかもしれません。 – moooeeeep

+0

@moooeeeep、初期化の問題ではありません! – Shahbaz

+0

@Shahbazしかし、後で譲渡する際に問題になるかもしれません。 – moooeeeep

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;}; 構造体abc xyz; int main(){ memset(&xyz、1、sizeof(struct xyz)); cout << xyz.x; //ごみを与えてください return 0;} –

+0

あなたは「私はCの構造体を持っています...」と述べました。あなたのコードはC++です。 – jacekmigacz

+0

Cコードを#includeし の#include検索 //名前空間stdを使用。 struct abc {int x; int y;}; 構造体abc xyz; int main(){ memset(&xyz、1、sizeof(struct abc)); // memset(&xyz、1、sizeof(struct xyz)); //不完全な型 'struct xyz'に 'sizeof'の無効なアプリケーションエラーを返します。printf( "xyz.x =%d"、xyz.x); //ゴミを与える return 0;} –

関連する問題