当前位置: 首页 > news >正文

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

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

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

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

http://www.dtcms.com/a/360826.html

相关文章:

  • Electron使用WebAssembly实现CRC-16 CCITT校验
  • 9.1C++——类中特殊的成员函数
  • 安卓悬浮球-3566-测试报告
  • vue社区网格化管理系统(代码+数据库+LW)
  • Adobe Acrobat打开pdf文件时闪退如何解决?
  • OpenCV-CUDA 图像处理
  • 论文阅读_TradingAgents多智能体金融交易框架
  • .net 微服务jeager链路跟踪
  • C++11 ——— lambda表达式
  • LeetCode 19: 删除链表的倒数第 N 个结点
  • GIT(了解)
  • 计算机网络---https(超文本传输安全协议)
  • Unity项目基本风格/规范
  • 三、SVN实践练习指南
  • 【项目思维】贪吃蛇(嵌入式进阶方向)
  • 函数、数组与 grep + 正则表达式的 Linux Shell 编程进阶指南
  • GPU 通用手册:裸机、Docker、K8s 环境实战宝典
  • 嵌入式碎片知识总结(二)
  • Shell编程(二):正则表达式
  • 至真科技西安分公司正式成立,赋能点金石业务增长新篇章!
  • 基于Spring Authorization Server的OAuth2与OpenID Connect统一认证授权框架深度解析
  • Linux -- 进程间通信【System V共享内存】
  • 基于llama.cpp在CPU环境部署Qwen3
  • JimuReport 积木报表 v2.1.3 版本发布,免费开源的可视化报表和大屏
  • 【Linux手册】Unix/Linux 信号:原理、触发与响应机制实战
  • 开源 C# .net mvc 开发(九)websocket--服务器与客户端的实时通信
  • Unity:XML笔记
  • 【基础】Three.js中如何添加阴影(附案例代码)
  • 基于SpringBoot的运动服装销售系统【2026最新】
  • 大型语言模型微调 内容预告(69)