偶然看到很久以前的一个代码片段,分享出来。
代码功能:展示各种数据结构占用的内存空间大小
要点1:sizeof是编译时转换为数字的,运行时已经相当于常量
要点2:宏变量转换字符串
#include <stdio.h>
#include <stdlib.h>
#define SPACE(T) printf("%20s:%5d B \n",#T,sizeof(T))
#define NEWLINE() printf("\n")
int main(void)
{
char array[5];
void *void_pointer;
char *char_pointer = &array[0];
int a;
int *int_pointer;
int_pointer = &a;
SPACE(char);
NEWLINE();
SPACE(signed);
SPACE(unsigned);
NEWLINE();
SPACE(short);
SPACE(short int);
SPACE(int);
SPACE(long);
SPACE(long int);
NEWLINE();
SPACE(float);
SPACE(double);
SPACE(double long);
SPACE(long double);
NEWLINE();
SPACE(array); /*sizeof(char) * 5*/
SPACE(&array);
SPACE(array[0]);
SPACE(&array[0]);
SPACE(char_pointer);
SPACE(void_pointer);
SPACE(int_pointer);
NEWLINE();
NEWLINE();
SPACE(uint16);
return 0;
}
以上代码可以帮助了解编译平台对应的数据结构占用空间,很有帮助。
曾经遇到很变态的一种平台,CSR蓝牙开发的,一个char居然是2个byte
类似的,如何确定平台的大端小端模式呢?