方式一:
定义,初始化结构体变量分开
struct Student
{
char name[10];
char age;
};
struct Student stu;
方式二:
附加结构体变量初始化
struct Student
{
char name[10];
char age;
}stu;
方式三:
struct
{
char name[10];
char age;
}stu;
把结构体名称去掉,这样更简洁,不过也不能定义其他同结构体变量了。
结构体内部成员变量的赋值:
方式一:
struct Student stu = {"hyk", 25};
struct Student stu = {.age = 25, .name = "hyk"};方式二:
struct Student stu; strcpy(stu.name, "hyk"); stu.age = 25;
方式三:
struct Student stu = { "hyk", 25 };
struct Student stu2 = stu;// 实际是两个结构体内存的拷贝,将stu内存的值拷贝给了stu2,如果结构体成员有指针元素,那么就不能直接赋值。
一个结构中可以有数组成员,也可以有指针成员,如果是指针成员结构体成员在初始化和赋值的时候就需要提前为指针成员分配内存。
定义一个结构体时可以指定具体元素的位长。
struct Test{
char a : 2;//指定元素为2位长,不是2个字节长
};
struct Student
{
int a[3];
int b;
};
int main() {
struct Student stu[3] = {
{ {1, 2, 3 }, 10 },
{ {4, 5, 6 }, 11 },
{ {7, 8, 9 }, 12 }
};
// 可以简写为:
struct Student stu[3] = {
{ 1, 2, 3, 10 },
{ 4, 5, 6, 11 },
{ 7, 8, 9, 12 }
};
return 0;
}
struct Student stu; struct Student *p = &stu; p->age = 26;
栈数组:
struct Student
{
int a;
int b;
};
int main() {
struct Student stu[3];
struct Student *p = stu;
int i;
for (i = 0; i < 3; i++) {
p->a = 10 + i;
p->b = 20 + i;
p++;
}
printf("%d,%d\n", stu[0].a, stu[0].b);
printf("%d,%d\n", stu[1].a, stu[1].b);
printf("%d,%d\n", stu[2].a, stu[2].b);
return 0;
}
运行结果:
堆数组:
struct Student
{
int a;
int b;
};
int main() {
struct Student *p;
p = malloc(sizeof(struct Student) * 3);
struct Student *arr = p;//arr指针记录了p的初始指针
p->a = 1;
p->b = 2;
p++;// 导致p指针的位置发生偏移,
p->a = 3;
p->b = 4;
printf("%d,%d\n", arr[0].a, arr[0].b);
printf("%d,%d\n", arr[1].a, arr[1].b);
//free(p);// 因为p的指针发生偏移,free(p)会发生异常
free(arr);// 可以正常释放malloc申请的堆内存
return 0;
}
运行结果:
结构体嵌套对齐图解:
原文地址:http://blog.csdn.net/wuseyukui/article/details/46291735