Welcome

首页 / 软件开发 / C语言 / 学点C语言(15):数据类型 - sizeof(检测类型大小)

学点C语言(15):数据类型 - sizeof(检测类型大小)2010-04-30 博客园 万一获取类型大小的变量最好不是 int 类型, 而是 size_t 类型;

size_t 在 stdio.h、stddef.h 都有定义.

1. 获取已知类型的大小:

#include <stdio.h>
#include <stddef.h>

int main(void)
{
char n = 2;
size_t size;

size = sizeof(char);
printf("%*u: char ", n,size);

size = sizeof(unsigned char);
printf("%*u: unsigned char ", n,size);

size = sizeof(short);
printf("%*u: short ", n,size);

size = sizeof(unsigned short);
printf("%*u: unsigned short ", n,size);

size = sizeof(int);
printf("%*u: int ", n,size);

size = sizeof(unsigned);
printf("%*u: unsigned ", n,size);

size = sizeof(long);
printf("%*u: long ", n,size);

size = sizeof(unsigned long);
printf("%*u: unsigned long ", n,size);

size = sizeof(long long);
printf("%*u: long long ", n,size);

size = sizeof(unsigned long long);
printf("%*u: unsigned long long ", n,size);

size = sizeof(float);
printf("%*u: float ", n,size);

size = sizeof(double);
printf("%*u: double ", n,size);

size = sizeof(long double);
printf("%*u: long double ", n,size);

size = sizeof(wchar_t);
printf("%*u: wchar_t ", n,size);

getchar();
return 0;
}