using sizeof and strlen

本文探讨了C语言中strlen与sizeof函数在处理字符数组时的不同行为。通过实例对比,揭示了两者在计算数组长度上的差异,并解释了这些差异的原因。

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

/*  * Author: zhoufan   * data  : 06/07/2008 just before the 08 Europen Cup :)  * e-mail: zhoufanking@hotmail.com  */   /* Purpose:  * 	using strlen and sizeof on a char array, sometimes make us obbsession.  *  *			1>If we define char buffer[10], strlen(buffer) returns 1.   * 			  For there is only a character '/0' in the buffer.But sizeof(  * 			  buffer) will return 10. Because the memory was alloced to 'buffer'  * 			  yet.  * 			2>If we define char buffer[] = "hello", strlen(buffer) returns 5.  * 			  Here it ignore the '/0' character. The sizeof(buffer) returns 6,because  * 			  plusing one more byte for '/0';  * 			3>If you define a function to calculate the array's length like following:  * 			  size_t arrsize( char *buffer )  * 			  {  * 				return ( sizeof(*buffer) );  * 			  }  * 			  you will find that you can't get what you want! The return value equals to  * 			  sizeof(buffer[0]);Under this situation, the function return the amount of   * 			  the memory space this array's type occupied. If you use sizeof(buffer) in   * 			  the function above, it will return 4, woa... why! Because the pointer 'buffer'  * 			  point to an array itself occupies 4 bytes.  * 			4>You can only use sizeof on variable, struct, union whose size could be determined  * 			  during the compilling period!   */  #include  #include   #define P(NAME,TYPE,SIZE) printf("%s size from %s is %d/n",NAME,TYPE,SIZE)  int _szsize(char * buffer) { 	if( NULL == buffer) 		perror(" the buffer could not be a NULL pointer!/n"); 	P("*buff","sizeof in a function",sizeof(*buffer)); 	return 0; }  int main( int argc , char ** argv ) { 	char buf[]= "hello!"; 	  	P("buf","sizeof",sizeof(buf)); 	 	P("buf[0]","sizeof buf[0]", sizeof(buf[0]));  	P("buf","strlen",strlen(buf));	  	_szsize(buf);  	return 0; } 	 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值