Consider the following C program segment:
char p[20]; int i;
char* s = "string";
int length = strlen(s);
for(i = 0; i < length; i++)
p[i] = s[length-i];
printf("%s", p);The output of the program is:
View worked solution
Answer: D
Let's trace the execution of the given C program segment step-by-step:
- The string pointer
spoints to the string literal"string". - The length of the string
sis calculated usingstrlen(s), which is 6 (excluding the null terminator'\0'). - The characters of
sare indexed from0to6as follows:s[0] = 's',s[1] = 't',s[2] = 'r',s[3] = 'i',s[4] = 'n',s[5] = 'g's[6] = '\0'(the null terminator)
- The loop runs for to ():
- For :
p[0] = s[6 - 0] = s[6] = '\0' - For :
p[1] = s[5] = 'g' - For :
p[2] = s[4] = 'n' - For :
p[3] = s[3] = 'i' - For :
p[4] = s[2] = 'r' - For :
p[5] = s[1] = 't'
- For :
After the loop finishes, the array p contains {'\0', 'g', 'n', 'i', 'r', 't', ...}.
When printf("%s", p) is called, it starts printing characters from the beginning of the array p until it encounters the null character ('\0'). Since the very first element p[0] is '\0', the printing terminates immediately, and no output is printed.
Therefore, the correct option is D.
Free practice · Your answers on this page are not saved.
