结构体
#include <stdio.h>
#include <string.h>
// struct 是一个C语言的一个关键字,用来声明一个结构体类型
// 声明了一个名字叫 student 的结构体类型
// 有两个成员,分别是整型的 id(学号) 字符数组 name(名字)
// struct 只是声明了这样一种数据类型,和普通的数据类型比如int、char
// 一样本身是没有分配空间的,只有在定义变量的时候才会为变量分配空间
struct student
{
int id;
char name[20];
}; //用struct 声明类型的时候要有 ;号,和函数相区分
#if 0
// 变量定义2:直接在结构类型声明的时候定义变量
struct teacher
{
int id;
char name[20];
}t1,t2; // 定义了两个老师的变量 变量名叫 t1、t2
// 变量定义3:结构类型可以不要名字,也就是说不能在其他地方使用了
// 只能在类型声明的时候定义变量
struct
{
int a;
int b;
}a, b; // 定义结构体变量a和b
//
int main()
{
// 结构体的变量定义
// 定义了一个student结构体变量 变量名叫 stu
// 用结构体定义变量的时候,类型要写完整,struct 关键字不能丢
// student stu2; struct 不能丢
struct student stu;
return 0;
}
#endif
// 结构体变量的初始化和成员使用
int main1()
{
// 定义结构体变量并且初始化
struct student stu = {1234, "xiaoming"};
struct student stu2 = {.name="xiaohong", .id=1234};
// 结构的成员变量的使用,结构变量使用成员变量,需要点 . 指明使用的是哪一个成员
printf ("id = %d, name = %s\n", stu.id, stu.name);
}
int main()
{
struct student stu;
// 结构体变量使用
stu.id = 1224;
strcpy(stu.name, "hello");
printf ("id = %d, name = %s\n", stu.id, stu.name);
}
结构体的内存对齐
#include <stdio.h>
struct A
{
char ch1;
char ch2;
};
struct B
{
int a;
int b;
};
struct C
{
char ch1;
//char ch2;
short sh;
int a;
//char ch3;
};
struct D
{
char ch;
int a;
short sh;
char ch2;
};
struct E
{
char ch;
double d;
};
int main()
{
printf ("%d\n", sizeof(struct A));
printf ("%d\n", sizeof(struct B));
printf ("%d\n", sizeof(struct D));
printf ("%d\n", sizeof(struct E));
return 0;
}