C語言_結構體的4種定義初始化方式及案例

王騰發表於2018-01-03

結構體是一種構造資料型別 (構造資料型別:陣列型別、結構體型別(struct)、共用體型別(union))。用途:把不同型別的資料組合成一個整體,通俗講就像是打包封裝,把一些有共同特徵(比如同屬於某一類事物的屬性,往往是某種業務相關屬性的聚合)的變數封裝在內部,通過一定方法訪問修改內部變數。

第一種:

#include <stdio.h>
#include <string.h>
int main()
{
 struct PERSON{
     int age;
     int height;
     char name[15];
 }p1;
    p1.age = 28;
    p1.height = 178; 
    strcpy(p1.name, "phper");
printf("%d,%d,%s",p1.age,p1.height,p1.name);
}

第二種:

#include <stdio.h>
#include <string.h>
struct PSERSON{
    int age;
     int height;
     char name[15];
}p1={
    age:28,
    height:178,
    name:"phper"
};
printf("%d,%d,%s",p1.age,p1.height,p1.name);
}

第三種:

#include <stdio.h>
#include <string.h>
struct PSERSON{
    int age;
     int height;
     char name[15];
}p1={
    .age = 28,
    .height = 178,
    .name = "phper"
};
printf("%d,%d,%s",p1.age,p1.height,p1.name);
}

第四種:

#include <stdio.h>
#include <string.h>
struct PSERSON{
    int age;
     int height;
     char name[15];
}p1={28,178,"phper"};
printf("%d,%d,%s",p1.age,p1.height,p1.name);
}

  結果 

 小案例:

#include <stdio.h>
#include <string.h>
struct TEST
{  
    int age;
    int height;
    char name[15]; 
};  
      
void function_print(struct TEST p1)  
{  
    printf("%d\n",p1.age);  
    printf("%d\n",p1.height); 
    printf("%s\n",p1.name);   
}  
      
int main()
{  
    struct TEST test={28,178,"phper"};  
    function_print(test);  
    return 0;  
} 

結果:

---------再來一個案例結合註釋吸收一下---------

#include <stdio.h>  
  
int main() {  
    //定義結構體型別  
    struct Person  
    {  
        int age;
        int height;
        char *name;  
    };  
    //初始化的4種方式  
    //1.定義的同時初始化  
    struct Person p1 = {28,178,"phper"};  
      
    //2.先定義再逐個初始化  
    struct Person p2;  
    p2.age = 28;  
    p2.height = 178;  
    p2.name = "phper";  
    
    //3.先定義再一次性初始化  
    struct Person p3;  
    p3 = (struct Person){28,178,"phper"};  
      
    //注意:結構體和陣列在這裡的區別,陣列不能先定義再進行一次性初始化  
    //結構體要明確的告訴系統{}中是一個結構體  
      
    //4.指定將資料賦值給指定的屬性  
    struct Person p4 = { .age=28 , .height=178, .name="phper"};  
    //列印結構體中取資料 //拿p4測試 
    printf("%d\n",p4.age);
    printf("%d\n",p4.height);
    printf("%s\n",p4.name);
     
    return 0;  
}  

 

相關文章