using sizeof and strlen

/*  * 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; } 	 
   
   
  
  
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值