Search code examples
clinuxsizeofstrlen

difference between sizeof and strlen in C linux


The first printf statement is giving output 3 and second giving 20. Can anybody please explain what's the difference between the two here?

char frame[20],str[20];
printf("\nstrlen(frame)= %d",strlen(frame));
printf("\nsizeof(frame) = %d",sizeof(frame));

Thanks :)


Solution

    1. Because the contents of frame is not initialized, which means it is not a valid C string, so strlen(frame) could return any value, or crash. Actually, its behavior is undefined in this case.

    2. Because frame is an array of 20 characters, therefore sizeof(frame) will return 20 * sizeof(char), which will always be 20 (sizeof(char) always equals 1).