Consider the following C program. #include<stdio.h> #include<string.h> int…

2017

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 _______

Attempted by 139 students.

Show answer & explanation

Correct answer: 2

Key idea: In C, the expression a[b] is defined as *(a + b), so 2[p] is the same as p[2] and 6[p] is the same as p[6].

Given the string:

  • c points to "GATECSIT2017" with indices 0..11: 0:G 1:A 2:T 3:E 4:C 5:S 6:I 7:T 8:2 9:0 10:1 11:7

Compute the subexpressions:

  • p[2] is the character 'T' (ASCII 84).

  • p[6] is the character 'I' (ASCII 73).

  • So the pointer expression becomes c + 84 - 73 - 1 = c + 10.

c + 10 points to the character at index 10, which is '1'. The substring starting there is "17", so its length is 2.

Therefore the program prints: 2

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir