Confusion in data types in a 2D array

前端 未结 2 1588
我寻月下人不归
我寻月下人不归 2020-12-15 13:30

Here is a code which print the address of the first element of an 2D array followed by an addition of 1. Though all 4 base addresses are same but their addition with 1 is ob

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 13:51

    If you compile this as C++, you can use the typeid operator from the typeinfo STL library to get this information. For example, running this

    #include 
    #include 
    
    void main()
    {
         int array[4][3];
         printf("array %s\n",typeid(array).name());   //of type int(*)[3]
         printf("array+1 %s\n",typeid(array+1).name());
         printf("&array %s\n",typeid(&array).name());   //....???
         printf("&array+1 %s\n",typeid(&array+1).name());
         printf("array[0] %s\n",typeid(array[0]).name());    //of type int*
         printf("array[0]+1 %s\n",typeid(array[0]+1).name());
         printf("&array[0] %s\n",typeid(&array[0]).name()); //....???
         printf("&array[0]+1 %s\n",typeid(&array[0]+1).name());
    }  
    

    Gave me the following results

    array int [4][3]
    array+1 int (*)[3]
    &array int (*)[4][3]
    &array+1 int (*)[4][3]
    array[0] int [3]
    array[0]+1 int *
    &array[0] int (*)[3]
    &array[0]+1 int (*)[3]
    

    This explains why adding 1 can increase the pointer by 4 bytes (a single int), 12 bytes (int[3]) or by 48 bytes (int[4][3]).

提交回复
热议问题