C语言面试题——sizeof的注意点

首先sizeof在C语言里是关键字,而不是一个函数,下面的语句执行之后,i的值是保持不变的,

j = sizeof(++i + ++i);

下面是C语言里部分数据类型的sizeof的值:

下面是一道C语言的面试题:

#include <stdio.h>
#include <string.h>

char str[] = "Hello";

struct size_b{
	float f;
	char p;
	int a[3];
}block;

struct flag_s1{
	char ch, *ptr;
	union{
		short a, b;
		unsigned int c : 2;
		unsigned int d : 1; 
	}u;
	struct flag_s1 *next;
}s1;

//the difference between sizeof and strlen() 
void func(char *fstr)
{
	printf("sizeof(fstr) = %d\n",sizeof(fstr));
	printf("strlen(fstr) = %d\n",strlen(fstr));
}

int main(void)
{
	printf("sizeof(str) = %d\n",sizeof(str));
	printf("sizeof(block) = %d\n",sizeof(block));
	//printf("sizeof(sizeof_b) = %d\n",sizeof(size_b)); wrong usage
	printf("sizeof(s1) = %d\n",sizeof(s1));
	func(str);

	
	return 0;
}
结果:
sizeof(str) = 6
sizeof(block) = 20
sizeof(s1) = 16
sizeof(fstr) = 4
strlen(fstr) = 5
请按任意键继续. . .

这里稍作解释:
指针大小在C编译器里始终是一个定值,若cpu是32位的,则指针大小的值为4(bytes),因为指针保存的只是地址而已,对于结构体block的大小,是这么计算的:4+4+3*4=20,这里还设计到内存对齐char p占用4个字节,结构体s1是:4(ch)+4(ptr)+2(a)+2(b)+4(next)=16;
最后提一点,strlen是求字符串的长度,不包括字符串的‘\0’,所以他的值比sizeof的值小一。

posted @ 2012-07-06 16:39  wdliming  阅读(152)  评论(0编辑  收藏  举报