结构体成员大小及内存对齐练习
方式一:动态内存分配(使用 malloc)
#include <stdio.h>
#include <stdlib.h> // 需要包含 stdlib.h 来使用 mallocstruct Test
{int num;char *pcName;short sDate;char cha[2];short sBa[4];
} *p;int main()
{// 动态分配内存并初始化p = (struct Test *)malloc(sizeof(struct Test));// 初始化结构体成员p->num = 10;p->pcName = "Hello";p->sDate = 2023;p->cha[0] = 'A';p->cha[1] = 'B';for(int i = 0; i < 4; i++) {p->sBa[i] = i + 1;}printf("%d\n", sizeof(struct Test)); // 输出 32printf("%p\n", p + 0x1); // 输出 p 的地址加上 32 字节的地址// 不要忘记释放内存free(p);printf("%d\n", sizeof(p)); // 输出 8printf("%d\n", sizeof(*p)); // 输出 32return 0;
}
方式二:静态分配(使用栈上的变量)
#include <stdio.h>struct Test
{int num;char *pcName;short sDate;char cha[2];short sBa[4];
} *p;int main()
{// 创建一个结构体实例struct Test test_instance;// 初始化结构体成员test_instance.num = 10;test_instance.pcName = "Hello";test_instance.sDate = 2023;test_instance.cha[0] = 'A';test_instance.cha[1] = 'B';for(int i = 0; i < 4; i++) {test_instance.sBa[i] = i + 1;}// 让指针 p 指向这个实例p = &test_instance;printf("%d\n", sizeof(p)); // 输出 8printf("%d\n", sizeof(*p)); // 输出 32printf("%d\n", sizeof(struct Test)); // 输出 32printf("%p\n", p + 0x1); // 输出 p 的地址加上 32 字节的地址return 0;
}
在这两种方式中,我都初始化了结构体的各个成员:
num
设置为 10pcName
指向字符串 “Hello”sDate
设置为 2023cha
数组设置为 [‘A’, ‘B’]sBa
数组设置为 [1, 2, 3, 4]
需要注意的是,在动态分配的方式中,我们使用了 malloc
来分配内存,并在使用完毕后调用 free
来释放内存,这是良好的编程实践,可以防止内存泄漏。
在静态分配的方式中,结构体实例是在栈上分配的,不需要手动释放内存,当 main
函数结束时,它会自动被回收。