C语言_结构体的4种定义初始化方式及案例

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了C语言_结构体的4种定义初始化方式及案例脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

结构体是一种构造数据类型 (构造数据类型:数组类型、结构体类型(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);
}

结果

C语言_结构体的4种定义初始化方式及案例

小案例:

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

结果:

C语言_结构体的4种定义初始化方式及案例

---------再来一个案例结合注释吸收一下---------

#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("%dn",p4.age);
    printf("%dn",p4.height);
    printf("%sn",p4.name);
     
    return 0;  
}  

脚本宝典总结

以上是脚本宝典为你收集整理的C语言_结构体的4种定义初始化方式及案例全部内容,希望文章能够帮你解决C语言_结构体的4种定义初始化方式及案例所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。