结构体成员大小及内存对齐练习

方式一:动态内存分配(使用 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 设置为 10
  • pcName 指向字符串 “Hello”
  • sDate 设置为 2023
  • cha 数组设置为 [‘A’, ‘B’]
  • sBa 数组设置为 [1, 2, 3, 4]

需要注意的是,在动态分配的方式中,我们使用了 malloc 来分配内存,并在使用完毕后调用 free 来释放内存,这是良好的编程实践,可以防止内存泄漏。

在静态分配的方式中,结构体实例是在栈上分配的,不需要手动释放内存,当 main 函数结束时,它会自动被回收。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值