简体   繁体   中英

Pointer to Array confusion

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 using printf("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;
}

`

The expression ptr2arr[0] is the same as *ptr2arr , so it dereferences the pointer to array of 3 int s, 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 int s, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM