News:

Download Pelles C here: http://www.smorgasbordet.com/pellesc/

Main Menu

printf() :)

Started by Sango, September 28, 2011, 10:23:47 AM

Previous topic - Next topic

Sango

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

TimoVJL

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;
}
May the source be with you

Sango

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

DMac

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').
No one cares how much you know,
until they know how much you care.

CommonTater

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?






Sango

#5
Thanks DMac

CommonTater check this out       http://www.gateforum.com/gatepapers/CS-GATE-2011.pdf

question no 10