对于结构体内存地址的连续性问题测试
代码如下,编辑器是为mingw32
/**
********************************************************
测试:关于结构体内存对齐和内存地址连续的问题
***********************************************************
*/
#include <stdio.h>
#pragma pack(push)
#pragma pack(1)
typedef struct _GPIO{
int num;
char ch;
char hj;
int key;
}GPIO;
#pragma pack(pop)
typedef struct _USART{
int num;
char ch;
char hj;
int key;
}USART;
int main(void)
{
GPIO gpio;
USART usart;
printf("内存对齐的简单测试 \n");
printf("\r\n sizeof(int) = %d ",sizeof(int));
printf("\r\n sizeof(char) = %d ",sizeof(char));
printf("\r\n sizeof(gpio) = %d ",sizeof(gpio));
printf("\r\n sizeof(usart) = %d ",sizeof(usart));
printf("内存连续的简单测试 \n");
printf("\r\n gpio 0X%04X 0X%04X 0X%04X 0X%04X",&gpio.num,&gpio.ch,&gpio.hj,&gpio.key);
printf("\r\n usart 0X%04X 0X%04X 0X%04X 0X%04X",&usart.num,&usart.ch,&usart.hj,&usart.key);
return 0;
}
输出结果如下
内存对齐的简单测试
sizeof(int) = 4
sizeof(char) = 1
sizeof(gpio) = 10
sizeof(usart) = 12
内存连续的简单测试
gpio 0X60FEA6 0X60FEAA 0X60FEAB 0X60FEAC
usart 0X60FE98 0X60FE9C 0X60FE9D 0X60FEA0
分析结果如下
- struct的内存地址是连续的,与结构定义结构体变量的顺序相同;