in Programming in C edited by
27,648 views
69 votes
69 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 _______

in Programming in C edited by
by
27.6k views

4 Comments

what would be the answer if we use sizeof() instead of strlen?

as the expression will evaluate to address so the sizeof() will give sizeof pointer (4 bytes in my machine)
0
0
Please note here that you don’t really need to remember the ASCII values of T or I. Why?

Because you just have to know the number of alphabetical difference between the two characters T & I. The difference is simply 11 (you can even count it on your fingers). Assuming A → 1; B → 2; C → 3;….. Z → 26

I.e; what’s the difference between G & D ?
‘G’ – ‘D’:   7 – 4 = 3

This intuition would come in handy in the exam environment.
1
1

Key concepts to note:

  1. 2[p] = *[p+2] = p[2]
  2. 6[p] = *[p+6] = p[6]

%s of (c+10) is 17, strlen in int will be 2.

0
0

13 Answers

5 votes
5 votes
Caption

Hope this helps!

1 vote
1 vote

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.

0 votes
0 votes

output is 2

0 votes
0 votes

answer is 2

Answer:

Related questions