0

By definition, it is a pointer variable that points to an array.

my code print the values of three element array . my question why the result is right usingprintf("Value at %p = %d\n", ptr2arr +i, *(ptr2arr[0]+i)); and wrong result except the first value while using printf("value at %p =%d\n" ,ptr2arr+i,*(ptr2arr[i]))


#include <stdio.h>
int main(int argc, char* argv[])
{
    int arr[3] = {1,2,3};
    int (*ptr2arr)[3];
    int i;
    ptr2arr = &arr;
    for(i = 0; i<3; i++)
    {
    printf("Value at %p = %d\n", ptr2arr +i, *(ptr2arr[0]+i));
    }
    printf("-------------------\n");
    for(i = 0; i<3; i++)
    {
    printf("value at %p =%d\n" ,ptr2arr+i,*(ptr2arr[i]));
    }
   return 0;
}

`

Elhaw
  • 325
  • 3
  • 18
  • I get a compilation error for `ptr2arr = &arr;`. `cannot convert 'int (*)[4]' to 'int (*)[3]' in assignment ptr2arr = &arr; `. – chmike Mar 06 '15 at 15:16
  • @chmike works with only a warning in C, in C++ you need to match the type. I guess it's just a typo, `int arr[4]` should be `int arr[3]`. – vsoftco Mar 06 '15 at 15:19
  • thnks i corrected the error – Elhaw Mar 06 '15 at 15:21
  • 1
    you seem to be thinking that `array[index]` is the same thing as `array + index`. it's not. rather, it's the same thing as `*(array + index)`. – The Paramagnetic Croissant Mar 06 '15 at 15:52
  • It's better to use '&ptr2arr[i]' rather than 'ptr2arr+i'. – Maged Elghareib Mar 06 '15 at 16:31
  • why it is better to use '&ptr2arr[i]' rather than 'ptr2arr+i'? – Elhaw Mar 06 '15 at 17:39
  • 1
    The `%p` specifier requires an argument of type `void*`. If you're printing a pointer of another type, you should cast it. You can probably get away without the cast on most systems, but there's no guarantee that `void*` and other pointer types have the same representation. – Keith Thompson Mar 06 '15 at 20:23

1 Answers1

2

The expression ptr2arr[0] is the same as *ptr2arr, so it dereferences the pointer to array of 3 ints, giving you effectively the array arr. Therefore, *(ptr2arr[0] + i) is the same as *(*ptr2arr + i) is the same as *(arr + i), which gives you the correct result.

Whereas in the line

printf("value at %p =%d\n" ,ptr2arr+i,*(ptr2arr[i]));

ptr2arr[i] (syntactic sugar for ptr2arr + i) "jumps" over arrays of 3 ints, so dereferencing it *(ptr2arr[i]) gives the arr[0] only when i = 0, otherwise it gives you what's located at the address arr + 3*sizeof i (undefined behaviour).


PS: the address passed to printf should be *ptr2arr + i, not ptr2arr + i.

See also dereferencing pointer to integer array for a bit more details.

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252