c言語構造体の初期化のいくつかの方式

2042 ワード

コンパイル環境:gcc version 5.4.020160609(Ubuntu 5.4.0-6 ubuntu 1~16.04.9)
テスト構造体宣言は次のとおりです.
struct person
{
  int age;
  char name[256];
}

1つ目:変数を定義し、[.]または[->]参照で初期化
// 
struct person p1;
p1.age = 20;
strcpy(p1.name, "xiaoming");
printf("age: %d
", p1.age); printf("name: %s
", p1.name); // struct person * p2 = NULL; p2 = (struct person *)malloc(sizeof(*p2)) if(p2 != NULL) { p2->age = 22; strcpy(p2->name, "xiaohong"); printf("age: %d
", p2->age); printf("name: %s
", p2->name); free(p2); p2 = NULL; }

2つ目:括弧に値を付けて初期化する
/** **/
// ,  
struct person p1 = {18, "xiaoming"};
printf("age: %d
", p1.age); printf("name: %s
", p1.name); // struct person p2; p2 = (struct person){19, "xiaohong"}; printf("age: %d
", p2.age); printf("name: %s
", p2.name); /** **/ // , struct person * p3 = NULL; p3 = (struct person *)malloc(sizeof(*p3)); if(p3 != NULL) { *p3 = (struct person){20, "xiaohua"}; printf("age: %d
", p3->age); printf("name: %s
", p3->name); free(p3); p3 = NULL; }

3つ目:カッコで[.]+[メンバー]linuxカーネルは、初期化順序に関係なく一般的に使用されます.繰り返しがある場合は、最後の初期化の値が有効になります.(ps:括弧の最後のカンマは加算可能か加算不可か)
/** **/
// 
struct person p1 = 
{
  .age = 20,
  .name = "xiaoming",
  .age = 21,
};
printf("age: %d
", p1.age); printf("name: %s
", p1.name); // struct person p2; p2 = (struct person) { .age = 21, .name = "xiaohong", }; printf("age: %d
", p2.age); printf("name: %s
", p2.name); /** **/ // struct person * p3 = NULL; p3 = (struct person *)malloc(sizeof(*p3)); if(p3 != NULL) { *p3 = (struct person) { .age = 22, .name = "xiaohua", }; printf("age: %d
", p3->age); printf("name: %s
", p3->name); free(p3); p3 = NULL; }