C语言-结构体的创建、取值、内存对齐

    技术2022-07-11  153

    C语言-结构体

    结构体声明

    #include <stido.h> struct People { char name[10]; int age; unsigned int birthday; char address[40]; float social_status; };

    定义结构体关键字 struct 结构体需要以 ; 结尾

    定义结构体

    int main (void) { struct People people; //该结构体为main函数内局部变量 }

    或在声明时定义:

    #include <stido.h> struct People { char name[10]; int age; unsigned int birthday; char address[40]; float social_status; } people; // 该结构体为全局变量

    初始化一个结构体变量

    struct People people = { "张无忌", 18, 19980807, "少林寺驻武当山办事处", 999.88 };

    引用结构体变量成员

    int main (void) { struct People people; printf("请输入姓名: "); scanf("%s", people.name); // 字符数组,名字就是地址,不需要&取址符& printf("请输入年龄: "); scanf("%d", &people.age); printf("请输入生日: "); scanf("%d", &people.birthday); printf("请输入住址: "); scanf("%s", people.address); printf("请输入身价: "); scanf("%f", &people.social_status); printf("\n============人员信息录入完毕===============\n"); printf("姓名: %s\n", people.name); printf("年龄: %d\n", people.age); printf("生日: %d\n", people.birthday); printf("住址: %s\n", people.address); printf("身价: %.2f\n", people.social_status); return 0; }

    内存对齐

    *为使cup对数据读取/处理的速度更快, 编译器对结构体的成员进行内存对齐。

    #include <stido.h> struct S { char a; int b; char c; }; int main (void) { struct S s = {'x', 520, 'o'}; printf("size of s = %ld\n", sizeof(s)); // 结果输出为: 12 }

    一个char类型占1个字节,一个int类型占4个字节, 所以我们预判结果为 6(1+4+1)。但实际结果却为12, 这是为什么呢? 是因为:

    对齐前: abc一个字节     四          个          字          节     一个字节 对齐后: a      b      c      一个字节                          四    个    字    节  一个字节                      

    (一般操作系统的对齐参数为4, a、c 后均由三个字节填充)

    将上述结构体调整:

    struct S2 { char a; char c; int b; }; int main (void) { struct S2 s2 = {'x', 'o', 520}; printf("size of s2 = %ld\n", sizeof(s2)); // 结果输出为: 8 } 对齐后: acb一个字节一个字节                              四      个      字        节     所以, 可以通过调整结构体成员的顺序, 来节省内存空间。
    Processed: 0.016, SQL: 9