edited by
27,909 views
70 votes
70 votes

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 _______

edited by

13 Answers

1 votes
1 votes

This question looks like a difficult one, but it’s actually rather simple if you know where to focus.

Like all GATE questions, simple questions are made intentionally obtuse with misdirections and useless ornaments.

 

This question tests your understanding of the function $strlen()$

$strlen()$ counts the character in a string (which is an array of characters in C) until it reaches the NULL character.

i.e, it returns the count of characters except for the NULL character.

 

Let’s evaluate: $c + 2[p] – 6[p] - 1$

  1. $c$  is the pointer to the head of the character array, i.e., a pointer to $c[0]$
     
  2. $2[p]$ is another way of writing $p[2]$ which is equilvalent to  $\text{‘T’}$ which in integer terms is $(65 + 19) = 84$
     
  3. $6[p]=p[6]= \text{‘I’}$ which in integer terms is $(65 + 8) = 73

 

$\therefore$ Solving the pointer arithmetic:

$(c + 84 – 73 - 1)$

$=(c + 10)$

which is the pointer to $\text{‘1’}$ (the 2nd last character)

$\therefore$ the call $strlen(c + 84 – 73 - 1) = strlen(\text{pointer to ‘1’})$

Since, $strlen()$ returns the count of chars till NULL is reached, it counts the chars $\{\text{‘1’, ‘7’}\}$ and returns $2$

 


 

NOTE:

So many useless statements in the question:

  1. $2[p]$ instead of $p[2]$
  2. $(int)$ typecast in printf which is unnecessary and just hides $strlen$ which is the main focus of this question

 

In programming questions, the trend seems to hide the important parts behind useless quirks of the C program, so if you're confused about what to focus on, you know where to look now.

Answer:

Related questions

30 votes
30 votes
11 answers
1
Madhav asked Feb 14, 2017
9,667 views
Consider the following function implemented in C:void printxy(int x, int y) { int *ptr; x=0; ptr=&x; y=*ptr; *ptr=1; printf(“%d, %d”, x, y); }The output of invoking $...
25 votes
25 votes
7 answers
2
Madhav asked Feb 14, 2017
11,945 views
Consider the following C program.#include<stdio.h int main () { int m=10; int n, n1; n=++m; n1=m++; n ; n1; n-=n1; printf(“%d”, n); return 0; }The output of the prog...
26 votes
26 votes
3 answers
4
khushtak asked Feb 14, 2017
5,833 views
Match the following:$$\begin{array}{|ll|ll|}\hline P. & \text{static char var ;} & \text{i.} & \text{Sequence of memory locations to store addresses} \\\hline Q. & \text...