NO

Author Topic: printf() :)  (Read 3825 times)

Sango

  • Guest
printf() :)
« 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

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: printf() :)
« Reply #1 on: September 28, 2011, 10:57:31 AM »
Pointer math, try with this.
Code: [Select]
#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

  • Guest
Re: printf() :)
« Reply #2 on: September 28, 2011, 06:27:34 PM »
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

Offline DMac

  • Member
  • *
  • Posts: 272
Re: printf() :)
« Reply #3 on: September 28, 2011, 09:45:01 PM »
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

  • Guest
Re: printf() :)
« Reply #4 on: September 28, 2011, 09:53:45 PM »
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

  • Guest
Re: printf() :)
« Reply #5 on: September 29, 2011, 06:03:06 AM »
Thanks DMac

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

question no 10
« Last Edit: September 29, 2011, 06:18:14 AM by Sango »