arrays and pointers

This is a discussion on arrays and pointers within the C Programming forums, part of the General Programming Boards category; This was an exam problem that I still don't really understand Code: int main () int a[10] = {1,2,3,4,5,6,7,8,9,10}; int ...

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    23

    arrays and pointers

    This was an exam problem that I still don't really understand
    Code:
    int main ()
    int a[10] = {1,2,3,4,5,6,7,8,9,10};
    int *ptr = (int*)(&a + 1);
    printf("%d %d, *(a+1), *(ptr-5) );
    return 0;
    Asking for the output

    I understand that *(a+1) == 2
    but
    how does *(ptr-5) == 6?

    It makes sense to me that *(ptr+5) == 6.. but dont know how *(ptr-5) == 6?

    thanks in advance

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    2,610
    Try print the result of this line

    printf("%p %p\n", &a+1, a+1);

    The type of &a is not the same as a.

    &a+1 is just passed the end of the array a
    a+1 is the second element in the array a

    Tim S.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the Universe is winning." Rick Cook

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,045
    Right, &a is pointer to int[10]. incrementing a pointer moves it by size of the type it points to, in this case sizeof(a) is 10*sizeof(int). The rest is strait forward.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with pointers and arrays
    By fusionplus in forum C Programming
    Replies: 5
    Last Post: 09-18-2011, 07:35 PM
  2. Pointers to pointers with arrays
    By Nurumla in forum C Programming
    Replies: 3
    Last Post: 07-18-2011, 11:53 PM
  3. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  4. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 04:31 AM
  5. pointers and arrays
    By onthewaytoC in forum C Programming
    Replies: 8
    Last Post: 06-08-2005, 06:13 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21