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

1932

被折叠的 条评论
为什么被折叠?



