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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

第二种语法表示

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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

第三种方式

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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

第四种方式

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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

C++语言结构体语法

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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值