Wednesday, January 6, 2010

Strlen() Vs sizeof()

strlen Vs sizeof

char mystr[100]="test string";

defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

/* strlen example */
#include
#include

int main ()
{
char szInput[256];
printf ("Enter a sentence: ");
gets (szInput);
printf ("The sentence entered is %u characters long.\n",strlen(szInput));
return 0;
}

Output:

Enter sentence: just testing
The sentence entered is 12 characters long.

No comments:

Post a Comment