Aakash Chopra Aakash Chopra - 1 month ago 13
C Question

I need to know how the output was generated by this source code

#include <stdio.h>
int main()
{
char c[]="GATE2016";
char *p = c;
printf("%s",p+ p[3] - p[1]);
}


The output to the above source code is

2016


I don't have the slightest clue how that came. Also when I edit

char c[]="asdf2016"


the output shown is

`


Can anybody help me in this?

Answer

First of all p is a pointer to the first element of the array c, so whenever you pass p alone it is going to behave exactly the same way as if you passed c, that is it will read from the adress of p until it reaches the string terminator '\0' .

Now, some say that it depends on whether your code uses ASCII or EBCDIC or any other encoding. While it's not wrong, your code does not depend immediatly on this. What matters is that, in the case of your string "GATE2016" the characters 'A' and 'E'(which are the ones accessed in this bizarre-looking code in the printf call) come one after the other and that substracting A from E gives 4, you'll see why. For the sake of this example, I'll use ASCII.

In ASCII, the characters 'A' equals 65, and 'E' equals 69. So in the line

printf("%s",p+ p[3] - p[1]);

what you are actually doing can be translated as

printf("%s",p+ 'E' - 'A');

or simply

printf("%s",p+ 69 - 65);

which can be further simplified as

printf("%s",p + 4);

Now since the "%s" format of printf expects a pointer to the beginning of a string, what you are actually passing as an argument in this case is the address of p + 4 (which since it's a pointer, gets shifted by 4 memory slots), so you end up with position [4] as the beginning of the string (p + 4 == &p[4]), printf starts reading your string at position 4, which contains the 2 of 2016. From there it just reads until it reaches '\0' in you string and just prints out 2016, which also explains why it does not work with "asdf".

Just remember that characters in C are simply numbers, and that, in ASCII, writing 'A' is exactly the same as writing the number 65.