What is the output of this C code?
#include <stdio.h>
#include <string.h>
int main()
{
char *str = "x";
char c = 'x';
char ary[1];
ary[0] = c;
printf("%d %d", strlen(str), strlen(ary));
return 0;
}
Answer: D
Correct answer: 1 (undefined value)
strlen(str) is 1, since the literal "x" is two bytes - the character and its terminating null.
The second call is undefined behaviour. ary is a one-element array holding 'x' with no room for a terminator, so strlen reads past the end of the array looking for a null and returns whatever count it reaches. The value is unpredictable, and the program may crash. This is why a character array intended as a string must always be declared one element longer than the text it holds.
Please log in or register to report this question.