Pelles C forum
C language => Beginner questions => Topic started by: Sango on September 28, 2011, 10:23:47 AM
-
hi!
please help me out with
char c[]="GATE2011";
char *p=c;
printf("%s",p+p[3]-p[1]);
0/P=2011
i don't know how p+P[3]-p[1] executes
-
Pointer math, try with this.
#include <stdio.h>
int main(int argc, char **argv)
{
char c[] = "GATE2011";
char *p = c;
printf("%s\n", p + p[3] - p[1]);
printf("%s\n", p + 'E' - 'A');
return 0;
}
-
thanks for the reply :)
i got that.
but my question was p+P[3]-p[1] is evaluated
i mean p=GATE2011, P[3]=E and p[1]=A
so how p+P[3]-p[1] results 2011
-
if you look at an ASCII table you will notice that the character displayed to you as an 'A' is 65 and the character displayed to you as an 'E' is 69. Therefore 69 - 65 = 4 the index of the first ASCII numeric character in the original string. The character '2' by the way is in actuality 50 (or in Hex 0x32. It's handy to remember that 0x30 - 0x39 represent the characters '0' - '9').
-
Hi Sango...
What you've got there is what I would class as "too clever" code... and it's only going to work in that one situation with that one bit of string data. As DMac explains it's using a math trick with the ASCII code to arrive at the offset of the 2 in 2011 for printf() to start printing.
About the only usefull point it makes is that printf() doesn't have to start at the beginning of a string. For a certainty it's of no use whatsoever in day to day programming tasks.
Out of curiosity... where did you find it?
-
Thanks DMac
CommonTater check this out http://www.gateforum.com/gatepapers/CS-GATE-2011.pdf
question no 10