Consider the following example:
/* Example for sizeof( ) , strlen( ) */ #includemain() { char String[]="Hello"; printf("\n SIZE OF String %d STRING LENGTH %d", sizeof( String ), strlen( String ) ); }
Result:
SIZE OF String 6 STRING LENGTH 5.
Every String contains a NULL character( '\0' ) at the end. The sizeof() function will include that NULL character also for calculating string size but strlen() function not.
Why is sizeof('a') not 1?
Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though it's different in C++).
Result:
In Turbo C output is: 2
In Turbo C++ output is: 1
1 comment:
Why strlen returns 5 and sizeof returns 6 is,
sizeof( ) gives the memory taken, so in a string NULL is also their in memory.
But, strlen( ) is a string processing function whose termination condition is NULL ('\0'). So it doesnt counts this NULL.
Another Example:
char String[ 5 ] = { 'H', 'e', 'l', 'l', 'o' };
which will return 5 for sizeof and unknown result for strlen. Because here there is no space for Null character as subcript is specified which limits string size.
Post a Comment