Question
Consider the following C program.
#include <stdio.h>
#include <string.h>
int main() {
char* c = "GATECSIT2017";
char* p = c;
printf("%d", (int) strlen(c + 2[p] - 6[p] - 1));
return 0;
}
The output of the program is
Official answer and solution
- Official answer
- 2
- From
- Official GATE 2017 answer key
Solution
Apply pointer arithmetic and the array subscript identity i[p] == *(p + i) == p[i] in C to determine the target string passed to strlen.
Given string literal c = "GATECSIT2017" and pointer p = c.
The characters and their indices in c are:
c[0] = 'G'c[1] = 'A'c[2] = 'T'c[3] = 'E'c[4] = 'C'c[5] = 'S'c[6] = 'I'c[7] = 'T'c[8] = '2'c[9] = '0'c[10] = '1'c[11] = '7'
Evaluate the pointer expression c + 2[p] - 6[p] - 1:
- By the commutative property of array indexing in C,
2[p]is equivalent top[2], which is the character'T'. - Similarly,
6[p]is equivalent top[6], which is the character'I'. - Using standard ASCII values:
'T' = 84and'I' = 73. - The difference is:
- Thus, the offset expression is:
- The pointer passed to
strlenisc + 10, which points to the substring"17". strlen("17")counts the two characters'1'and'7', returning 2.
2
Assuming 2[p] is invalid syntax in C; in standard C, E1[E2] is defined identically as *((E1) + (E2)).
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2017 Computer Science and Information Technology (CS) Session 2
- Question
- 55 of 65, printed as CS Q.55
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.