Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Explain this program.

  1. Oct 24, 2013 #1
    #include<stdio.h>
    void main()
    {
    char c[]="gate2011";
    char *p=c;
    printf("%s",p+p[3]-p[1]);
    }
     
  2. jcsd
  3. Oct 24, 2013 #2

    CompuChip

    User Avatar
    Science Advisor
    Homework Helper

    Doesn't look like rocket science. What do you think will happen? What actually happens when you run it?
     
  4. Oct 24, 2013 #3
    It apparently takes the adress of the string + 65-61= adr + 4. Now I don't know but this seems not aligned, but it means maybe adr + 4 bytes, hence it maybe prints '2011', but I have not checked this for real.
     
    Last edited: Oct 24, 2013
  5. Oct 24, 2013 #4

    CompuChip

    User Avatar
    Science Advisor
    Homework Helper

    The trick is the way that pointers and arrays are equivalent in C++.
    If you have an array
    Code (Text):
    int[] a;
    then a is a pointer to an int, and &a[4] and *(a + 4) both point to address of the 5th array element.
    So the pointer p points at the beginning of the string, p[4] - p[1] is the length of the memory block used by the first four characters and the sum is a pointer to the place in memory where the '2' is stored. Since strings are terminated by a null (\0) the statement is equivalent to
    Code (Text):

        char p[] = { '2', '0', '1', '1', '\0' };
        printf("%s", p);
     
    You could actually reach the same thing through
    Code (Text):

    #include<stdio.h>
    void main()
    {
        char c[]="gate2011";
        // No need to introduce a new name, c is already a char*
        // char* p = c;
        printf("%s", (c + 4));
    }
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Explain this program.
  1. Root programming (Replies: 3)

  2. Programming in mips (Replies: 1)

  3. Root programming (Replies: 3)

  4. Programming languages (Replies: 16)

  5. HMI programming (Replies: 1)

Loading...