C & C++: What is the difference between pointer-to and address-of array?

后端 未结 3 2014
情话喂你
情话喂你 2021-01-12 17:30

C++11 code:

int a[3];
auto b = a;       // b is of type int*
auto c = &a;      // c is of type int(*)[1]

C code:

int a[         


        
3条回答
  •  星月不相逢
    2021-01-12 18:09

    Consider this example:

    #include
    
    int main()
    {
        int myArray[10][10][10][10]; //A 4 Dimentional array;
    
        //THESE WILL ALL PRINT THE SAME VALUE
        printf("%d, %d, %d, %d, %d\n",
                myArray,
                myArray[0],
                myArray[0][0],
                myArray[0][0][0],
                &myArray[0][0][0][0]
              );
    
        //NOW SEE WHAT VALUES YOU GET AFTER ADDING 1 TO EACH OF THESE POINTERS
        printf("%d, %d, %d, %d, %d\n",
                myArray+1,
                myArray[0]+1,
                myArray[0][0]+1,
                myArray[0][0][0]+1,
                &myArray[0][0][0][0]+1
              );
    }
    

    You will find that all the 5 values printed in first case are all equal. Because they point to the same initial location.

    But just when you increment them by 1 you see that different pointers now jump (point) to different locations. This is because myArray[0][0][0] + 1 will jump by 10 integer values that is 40 bytes, while myArray[0][0] + 1 will jump by 100 integer values i.e by 400 bytes. Similarly myArray[0] + 1 jumps by 1000 integer values or 4000 bytes.

    So the values depend on what level of pointer you are referring to.

    But now, if I use pointers to refer all of them:

    #include
    
    int main()
    {
        int myArray[10][10][10][10]; //A 4 Dimentional array;
    
                int * ptr1 = myArray[10][10][10];
                int ** ptr2 = myArray[10][10];
                int *** ptr3 = myArray[10];
                int **** ptr4 = myArray;
    
        //THESE WILL ALL PRINT THE SAME VALUE
        printf("%u, %u, %u, %u\n", ptr1, ptr2, ptr3, ptr4);
    
        //THESE ALSO PRINT SAME VALUES!!
        printf("%d, %d, %d, %d\n",ptr1+1,ptr2+1,ptr3+1,ptr4+1);
    }
    

    So you see, different levels of pointer variables do not behave the way the array variable does.

提交回复
热议问题