What does the following fragment of C program print?
char c[] = "GATE2011";
char *p = c;
printf("%s", p + p[3] - p[1]);View worked solution
Answer: C
Let's analyze the given C program fragment step-by-step:
-
Array Initialization:
char c[] = "GATE2011";
This creates a character arrayccontaining the string"GATE2011"followed by a null terminator'\0':c[0] = 'G'c[1] = 'A'c[2] = 'T'c[3] = 'E'c[4] = '2'c[5] = '0'c[6] = '1'c[7] = '1'c[8] = '\0'
-
Pointer Assignment:
char *p = c;
The pointerppoints to the first element of the array, i.e.,&c[0]. -
Pointer Arithmetic:
The expression in the
printfstatement is:Substituting the values of
p[3]andp[1]:p[3]is'E'p[1]is'A'
'E' = 69and'A' = 65):Therefore, the expression simplifies to:
Since
ppoints toc[0],p + 4points toc[4]. -
Printing the String:
The
%sformat specifier prints the string starting from the memory addressp + 4(which is&c[4]) up to the null terminator.The characters starting from index 4 are
Thus, the output is'2','0','1','1', and'\0'.2011.
Free practice · Your answers on this page are not saved.
