Thread: arrays and pointers

  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
    4,183
    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.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    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, 05:31 AM
  5. pointers and arrays
    By onthewaytoC in forum C Programming
    Replies: 8
    Last Post: 06-08-2005, 06:13 PM