关于sizeof用法的补充

本文详细解析了C语言中sizeof运算符的工作原理及其在不同类型数据上的应用效果,包括基本数据类型、数组、指针、结构体等,并通过示例代码展示了实际运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.sizeof基础变量时,具体结果参见下方代码结果;

2.sizeof非字符串数组时,结果为数组所占总的字节大小;

3.sizeof字符串数组时,由数组和由指针初始化所得的结果不同,数组初始化所得结果为该数组所占总字节大小,指针初始化所得结果为4(指针本身所占内存长度),与《C专家编程》中描述一致;

4.sizeof指针时,所有指针结果均为4;

5.sizeof指针所指内容时,为该指针数据类型sizeof所得的结果;

6.sizeof结构体、共同体参见《C/C++数据对齐》一文;

7.对函数使用sizeof时,只能对有返回值的函数使用,且所得结果为返回值的sizeof值,而对返回空的函数取sizeof将会产生编译错误。


以下为测试代码与测试结果,编译器为VC8,VC的制定对齐值为8,而GCC的约定对齐值为4:

	struct B {  
		char b;  
		int a;  
		double d;
		short c;  
	};  

	B *pb = new B;
	int arrA[4] = {0};
	char *str1 = "string test";
	char str2[] = "string test";
		
	std::cout<<"sizeof(char):"<<sizeof(char)<<std::endl;
	std::cout<<"sizeof(unsigned char):"<<sizeof(unsigned char)<<std::endl;
	std::cout<<"sizeof(short):"<<sizeof(short)<<std::endl;
	std::cout<<"sizeof(unsigned short):"<<sizeof(unsigned short)<<std::endl;
	std::cout<<"sizeof(int):"<<sizeof(int)<<std::endl;
	std::cout<<"sizeof(unsigned int):"<<sizeof(unsigned int)<<std::endl;
	std::cout<<"sizeof(long):"<<sizeof(long)<<std::endl;
	std::cout<<"sizeof(unsigned long):"<<sizeof(unsigned long)<<std::endl;
	std::cout<<"sizeof(long long):"<<sizeof(long long)<<std::endl;
	std::cout<<"sizeof(unsigned long long):"<<sizeof(unsigned long long)<<std::endl;
	std::cout<<"sizeof(float):"<<sizeof(float)<<std::endl;
	std::cout<<"sizeof(double):"<<sizeof(double)<<std::endl;
	std::cout<<"sizeof(long double):"<<sizeof(long double)<<std::endl;
	std::cout<<"sizeof(struct B):"<<sizeof(B)<<std::endl;
	std::cout<<"sizeof(struct B*):"<<sizeof(pb)<<std::endl;
	std::cout<<"sizeof(struct *B):"<<sizeof(*pb)<<std::endl;
	std::cout<<"sizeof(arrA):"<<sizeof(arrA)<<std::endl;
	std::cout<<"sizeof(str1):"<<sizeof(str1)<<std::endl;
	std::cout<<"sizeof(str2):"<<sizeof(str2)<<std::endl;
	std::cout<<"sizeof(*str2):"<<sizeof(*str2)<<std::endl;
	std::cout<<"sizeof(std::string):"<<sizeof(std::string)<<std::endl;
	std::cout<<"sizeof(atoi(str2)):"<<sizeof(atoi(str2))<<std::endl;
	// std::cout<<"sizeof(f1()):"<<sizeof(f1())<<std::endl; // error here , f1() returns void
	system("pause");
	
	delete pb;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值