Are a, &a, *a, a[0], &a[0] and &a[0][0] identical pointers?

后端 未结 8 1557
南旧
南旧 2020-11-27 17:45

I have the following C program:

#include 

int main(){
    int a[2][2] = {1, 2, 3, 4};
    printf(\"a:%p, &a:%p, *a:%p \\n\", a, &a, *         


        
相关标签:
8条回答
  • 2020-11-27 18:29

    Because all expressions are pointing to the beginning of the array:

    a = {{a00},{a01},{a10},{a11}}
    

    a points to the array, just because it is an array, so a == &a[0]

    and &a[0][0] is positioned at the first cell of the 2D array.

    0 讨论(0)
  • 2020-11-27 18:33

    It is printing out the same values because they all are pointing to the same location.

    Having said that,

    &a[i][i] is of type int * which is a pointer to an integer.

    a and &a[0] have the type int(*)[2] which indicates a pointer to an array of 2 ints.

    &a has the type of int(*)[2][2] which indicates a pointer to a 2-D array or a pointer to an array of two elements in which each element is an array of 2-ints.

    So, all of them are of different type and behave differently if you start doing pointer arithmetic on them.

    (&a[0][1] + 1) points to the next integer element in the 2-D array i.e. to a[0][1]

    &a[0] + 1 points to the next array of integers i.e. to a[1][0]

    &a + 1 points to the next 2-D array which is non-existent in this case, but would be a[2][0] if present.

    0 讨论(0)
提交回复
热议问题