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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With