Consider the following C function C#include <stdio.h> int main(void) { char c[…
2017
Consider the following C function
C#include <stdio.h>
int main(void)
{
char c[ ] = "ICRBCSIT17";
char *p=c;
printf("%s", c+2[p] – 6[p] – 1);
return 0;
}
The output of the program is
- A.
SI
- B.
IT
- C.
TI
- D.
17
Attempted by 250 students.
Show answer & explanation
Correct answer: D
The expression inside printf is: c + 2[p] - 6[p] - 1
In C, the array subscript operator [] is commutative. This means a[i] is exactly the same as *(a + i) or i[a].
2[p]is equivalent top[2]. Looking at our table,p[2]is the character 'R'.6[p]is equivalent top[6]. Looking at our table,p[6]is the character 'I'.
Now, the expression becomes:
c + (ASCII value of 'R') - (ASCII value of 'I') - 1
We don't need to memorize the exact ASCII table, just the relative distance between letters:
'I' is the 9th letter, 'R' is the 18th letter.
The difference between 'R' and 'I' is 18 - 9 = 9.
Therefore:
'R' - 'I' = 9.
Plugging this back into our pointer expression:
c + 9 - 1 = c + 8
4. Final Result
The printf("%s", ...) function expects a pointer to a string. Since we calculated the pointer to be c + 8, it will start printing from index 8 of the array c until it hits the null terminator (\0).
Index 8 is '1'
Index 9 is '7'
Index 10 is '\0' (stops here)
Output: 17