C语言编程入门——结构体(上)

来源:互联网 发布:一体化指挥平台数据库 编辑:程序博客网 时间:2024/05/20 11:19
   


    在C语言中,结构体(struct)指的是一种数据结构,是C语言中聚合数据类型(aggregate data type)的一类。结构体可以被声明为变量、指针或数组等,用以实现较复杂的数据结构。结构体同时也是一些元素的集合,这些元素称为结构体的成员(member),且这些成员可以为不同的类型,成员一般用名字访问。

    结构体是自己定义的结构类型,为以后创建链表结点作铺垫。


定义结构体的三种方式:

# include <stdio.h>//第一种方式struct Student_1 //struct为定义结构体,Student_1为结构体名称,相当于int,变量在main()函数中定义,推荐使用。{int age;char sex;float score;};//第二种方式struct Student_2{int age;char sex;float score;} st2; //在定义结构体的同时定义了变量,相当于int i; 不推荐使用。//第三种方式struct //定义结构体变量没有写结构体名称,不推荐使用。{int age;char sex;float score;} st3;int main(void){Student_1 st1;return 0;}


结构体示例:

/*结构体的实质是根据需要自己定义一种复合的数据类型。*/# include <stdio.h>struct Student //定义结构体,Student为结构体名,即为新数据类型名。{int age; //定义结构体中的每一个成员。char sex;float score;}; //定义的是一种新的复合数据类型,在定义结构体时分号不能省int main(void){struct Student st1 = {19, 'F', 66.6}; //为结构体中的变量赋值。Student st2 = {20, 'F', 99}; //定义时结构体名即为变量类型,此语句类似于int i;      //但为表明定义的变量为结构体,前最好写上struct,即struct + 变量类型 + 变量名。return 0;}

结构体的赋值与输出:

# include <stdio.h>struct Student{int age;char sex;float score;}; int main(void){struct Student st1 = {19, 'F', 66.6}; //初始化,定义的同时赋初始值,且只能在定义的同时整体赋值。struct Student st2; //若在定义时没有赋值,则只能单项赋值,赋值格式为:结构体名.成员名 = X值。st2.age = 20;st2.sex = 'm';st2.score = 99;printf("%d, %c, %f\n", st1.age, st1.sex, st1.score); //结构体的输出。printf("%d, %c, %f\n", st2.age, st2.sex, st2.score);return 0;}


结构体中每一个成员的表示:

# include <stdio.h>struct Student{int age;char sex;float score;}; int main(void){struct Student st = {30, 78, 'F'};struct Student * pst = &st; //定义pst为结构体类型指针变量并赋值结构体变量st的地址。st.age = 20; //第一种方式:结构体变量名.成员名pst->age = 25; //第二种方式:指针变量名->成员名pst->score = 88.8F; //88.8在C语言中默认是double类型,若希望一个实数是float类型,则应在实数末尾加F或f,即88.8是double类型,88.8F或88.    //8f是float类型。printf("%d, %f\n", pst->age, st.score); //两种方式是等价的return 0;}/*pst->age 在计算机内部会被转化成(*pst).age,这就是->的含义。所以,pst->age 等价于(*pst).age,即st.age。*/


结构体示例:

# include <stdio.h>typedef struct Student //typedef 定义结构体类型。{char name[20];int age;float score;} Stu, * pStu; //Stu 等价于 struct Student,pStu 等价于 struct Student * ,用于快速定义。int main(void){Stu st;pStu pst;pst = &st;return 0;}


1 0
原创粉丝点击