开发者

how does following program work pointer manipulation [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

A c program from GATE paper

Here is a program which is working

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

The output开发者_Python百科 is

2011

Now comes the problem I am not able to understand the operation p+p[3]-p[1] what is that pointing to?

My understanding is when I declare some thing like

char c[]="GATE2011"

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


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

Anyone found writing this sort of thing in production code would be shot, though.


It's pretty horrid code. (p+p[3]-p[1]) is simply adding and subtracting offsets to p. p[3] is (char)'E', which is 69 in ASCII. p[1] is (char)'A', which is 65 in ASCII. So the code is equivalent to:

(p+69-65)

which is:

(p+4)

So it's simply offseting the pointer by 4 elements, before passing it to printf.

Technically, this is undefined behaviour. The first part of that expression (p+69) offsets the pointer beyond the end of the array, which is not allowed by the C standard.


That is

pointer + char - char

which has a pointer value

It's basic pointer arithmetic ...

You can add some parenthesis (in a different order than the language specifies but resulting in the same value) to make it easier to understand

pointer + (char - char)

or

p + ('E' - 'A')

or

p + 4

which is

&p[4]

or the string "2011".


Simple math.

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

The whole thing is p+'E'-'A' which is 'p+4', which points to the '2'.


#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
    i.e 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜