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;
}

`

7
  • I get a compilation error for ptr2arr = &arr;. cannot convert 'int (*)[4]' to 'int (*)[3]' in assignment ptr2arr = &arr; . Commented Mar 6, 2015 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]. Commented Mar 6, 2015 at 15:19
  • thnks i corrected the error Commented Mar 6, 2015 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). Commented Mar 6, 2015 at 15:52
  • 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. Commented Mar 6, 2015 at 20:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

in your 3rd line answer arr+i is equivalent to &[i] in this example not arr[i]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.