/* * 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; }
/* * 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 obbse