如果指针是C语言的灵魂,那么结构体就是C语言的肚子,数据的存储离不开结构体的运用。
要定义结构,需要使用到struct语句,struct语句可以定义一个包含多个不同数据类型的结构体。
栗子
#include<stdio.h>
#include<string.h>
#if 1
typedef struct student{
int id;
char name[10];
char sex;
}stu; //给结构体取别名为stu
#else
struct student{
int id;
char name[10];
char sex;
};
#endif
int main()
{
//struct student stu1; //定义stu1变量,类型为struct student,stu1就具有了struct student类型的结构
stu stu1; //定义stu1,类型为stu
stu1.id=2014;
strcpy(stu1.name,"zhangfei");
stu1.sex='m';
printf("value of id is:%d\n",stu1.id);
printf("value of name is:%s\n",stu1.name);
printf("value of sex is:%c\n",stu1.sex);
return 0;
}
我们使用成员运算符.号访问结构体成员。那么,stu1变量所占有的内存是否为结构体struct student内各个数据类型所占字节的和?
编译后,我们发现sizeof(stu1)=16。居然不是15。原来结构体在内存中存放是按单元存放的,每个单元多大取决于结构体中最大基本类型的大小。我们通过以下的表格可以快速理解
id | id | id | id |
name | name | name | name |
name | name | name | name |
name | name | sex |
再看这个例子
#include<stdio.h>
struct student{
char a;
int b;
int c;
}stu;
int main()
{
printf("sizeof stu is:%d\n",sizeof(stu));
return 0;
}
输出12。
a | |||
b | b | b | b |
c | c | c | c |
可以看到b会再开辟一个存储4字节存储单元,而不是放在a后面。
另外注意:定义结构体使用的是花括号{ },末尾记得加分号。
下一篇 C语言结构体指针