C语言学习笔记-结构体占用内存大小的计算
引言
结构体在C语言中虽然经常使用,但是怎么计算一个结构体占用多大的内存,很多C语言的新手都没注意过,其实C语言的语法简单,难就难在它更偏向于与底层,与内存打交道。对于嵌入式方面来说,对C语言的要求更高,因为有些硬件的内存并不像我们使用的电脑的内存那么充裕,所以需要节约内存。
结构体中同样的变量个数,却可能导致占用内存的大小不同。
例子
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// #pragma pack(8)
typedef struct a
{
int c;
double d;
char b[10];
}test1;
test1 e1;
printf("结构体 test1 占用空间大小为:%I64d\r\n", sizeof(test1));
printf("e1 的 c 的起始地址为:%p\r\n", &e1.c);
printf("e1 的 d 的起始地址为:%p\r\n", &e1.d);
printf("e1 的 b 的起始地址为:%p\r\n", &e1.b);
typedef struct b
{
double d;
int c;
char b[10];
}test2;
test2 e2;
printf("结构体 test2 占用空间大小为:%I64d\r\n", sizeof(test2));
printf