菜鸟笔记
提升您的技术认知

C/C++结构体语法总结

结构体简介

结构体属于聚合数据类型的一类,它将不同的数据类型整合在一起构成一个新的类型,相当于数据库中一条记录,比如学生结构体,整合了学号,姓名等等信息。结构体的好处就是可以对这些信息进行整体管理操作,类似面向对象中类的属性,有了结构体,我就可以更好抽象描述一个类别,个人感觉类就是由结构体发展而来的。在C/C++中,结构体声明的关键字为struct。

C语言结构体语法

第一种语法表示

struct 结构体名称{
   数据类型 member1;
   数据类型 member2;
};
这种方式在声明结构体变量时为:struct 结构体名称 结构体变量名
example :

#include<stdio.h>
struct Student{
    int sNo;
    char name[10];
};
int main(){
    struct Student stu;
    scanf("%d",&stu.sNo);
    scanf("%s",stu.name);
    printf("%d\n",stu.sNo);
}

第二种语法表示

typedef struct 结构体名称{
   数据类型 member1;
   数据类型 member2;
}结构体名称别名;
这种方式在声明结构体变量时有两种方式。

第一种:struct 结构体名称 构体变量名
第二种:结构体名称别名 结构体变量名

原因:这里使用了typedef关键字,此关键字的作用就是声明数据类型的别名,方便用户编程,所以这里用了之后,结构体名称别名就相当于struct 结构体名称。在声明结构体变量时,就无需写struct了。
example:

#include<stdio.h>
typedef struct Student{
    int sNo;
    char name[10];
}Stu;
int main(){
    struct Student stu;  //方式一
    Stu stu1;            //方式二
    scanf("%d",&stu.sNo);
    scanf("%s",stu.name);
    printf("%d\n",stu.sNo);
    scanf("%d",&stu1.sNo);
    scanf("%s",stu1.name);
    printf("%d\n",stu1.sNo);
}

第三种方式

struct 结构体名称{
   数据类型 member1;
   数据类型 member2;
}结构体变量名;

相当于:

struct 结构体名称{
   数据类型 member1;
   数据类型 member2;
};
struct 结构体名称 结构体变量名;

这种方式既定义了结构体名称,同时声明了一个结构体变量名。在其它地方也可以通过struct 结构体来再次声明其它变量,而第四种方法则不可以。
example:

#include<stdio.h>
struct Student{
    int sNo;
    char name[10];
}stu;      //此处stu 是变量名
int main(){
    scanf("%d",&stu.sNo);
    scanf("%s",stu.name);
    printf("%d\n",stu.sNo);
}

第四种方式

struct {
   数据类型 member1;
   数据类型 member2;
}结构体变量名;

此方式是匿名结构体,在定义时同时声明2个结构体变量,但不能在其它地方声明,因为我们无法得知该结构体的标识符,所以就无法通过标识符来声明变量。
example:

#include<stdio.h>
struct {
    int sNo;
    char name[10];
}stu,stu1;     //匿名结构体,同时定义了2个结构体变量
int main(){
    scanf("%d",&stu.sNo);
    scanf("%s",stu.name);
    printf("%d\n",stu.sNo);
    scanf("%d",&stu1.sNo);
    scanf("%s",stu1.name);
    printf("%d\n",stu1.sNo);
}

C++语言结构体语法

C++语言结构体语法的C大同小异,声明结构体变量时可以省略struct 其它无变化!
具体参照C语言部分,在用到“struct 结构体名称”时,可以简写为“结构体名称”来声明。