How the next manipulation of the program operation pointer works

Possible duplicate:
Program c from a GATE document

Here is a program that works

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

Output signal

 2011 

Now the problem is, I can’t understand the operation p + p [3] -p [1] what does this mean?

My understanding is when I declare something like

 char c[]="GATE2011" 

Then c is a pointer pointing to a string constant, and the line starts with G. In the next line *p=c; the p pointer points to the same address that c points to. So how does the above arithmetic work?

+4
source share
5 answers

This is pretty awful code. (p+p[3]-p[1]) simply adds and subtracts offsets by p . p[3] is (char)'E' , which is 69 in ASCII. p[1] is (char)'A' , which is 65 in ASCII. Thus, the code is equivalent to:

 (p+69-65) 

which the:

 (p+4) 

So this is just a pointer offset by 4 elements before passing it to printf .

Technically, this behavior is undefined. The first part of this expression ( p+69 ) shifts the pointer beyond the end of an array that is not permitted by the C standard.

+3
source

p[3] - 'E', p[1] - 'A'. The difference between ASCII codes A and E is 4, so p+p[3]-p[1] equivalent to p+4 , which in turn is equivalent to &p[4] , and therefore points to the character "2" in the char array.

Anyone who writes that it is written in production code will be removed.

+8
source

it

 pointer + char - char 

which has a pointer value

This basic pointer arithmetic ...

You can add some brackets (in a different order than the language indicates, but leading to the same meaning) to make it easier to understand

 pointer + (char - char) 

or

 p + ('E' - 'A') 

or

 p + 4 

which the

 &p[4] 

or the string "2011" .

+3
source

Simple math.

p[3] = 'E', p[1] = 'A'

All this is p+'E'-'A' , which is "p + 4", which points to "2".

0
source
 #include<stdio.h> int main () { char c[]="GATE2011"; char *p=c; // here you allocated address of character array c into pointer p printf("%s",p+p[3]-p[1]); /* p refers to the memory location of c[0],if you add any thing in p ie p+1 it becomes next block of memory,in this case p+p[3]-p[1] takes 4 bytes forward and gives 2011 as output */ } 
0
source

All Articles