Confusion in data types in a 2D array

前端 未结 2 1587
我寻月下人不归
我寻月下人不归 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:32

    Having int array[4][3]; the following applies

    array is an array with 4 elements. Each element is an array with 3 ints. In most circumstances using the name by itself makes the array decay to a pointer to its first element; then array becomes a pointer to arrays of 3 ints

    array + 1 is a pointer to an array of 3 ints. Here array decays to pointer and the 1 refers to array of 3 int

    &array is the address of the whole array. It points to objects of type array of 4 arrays of 3 ints

    &array + 1 is the 2nd (which really does not exist) element of a pseudo-array of arrays of 4 arrays of 3 ints

    array[0] is an array of 3 ints. It usually decays to a pointer to the first element

    array[0] + 1 points to the 2nd int in array[0]

    &array[0] address of an object of type array of 3 ints

    &array[0]+1 2nd element of an array of arrays of 3 ints

    PS. I'll try to make a drawing (ASCII) after lunch.


    Hmmm ... drawing is tough :)

    Before trying, I thought I could make a better drawing. This is the best I could come up with ...

    
        int array[4][3]        ........[aaabbbcccffffd]........
                                  where aaa, bbb, ccc, ffffd are arrays of 3 ints'
    
        the [] represent the object itself; the {} represent pointers.
    
        array (object)         ........[AAABBBCCCDDD]........       int[4][3]
        array (decayed)    ==> ........{aaa}bbbcccffffd........       int(*)[3]
    
        array + 1          ==> ........aaa{bbb}cccffffd........       int(*)[3]
    
        &array             ==> ........{aaabbbcccffffd}........       int(*)[4][3]
        &array + 1         ==> ........aaabbbcccffffd{xxxxxxxxxxxx}........       int(*)[4][3]
    
        array[0] (object)      ........[AAA]bbbcccffffd........       int[3]
        array[0] (decayed) ==> ........{a}aabbbcccffffd........       int*
    
        array[0] + 1       ==> ........a{a}abbbcccffffd........       int*
    
        &array[0]          ==> ........{aaa}bbbcccffffd........       int(*)[3]
        &array[0] + 1      ==> ........aaa{bbb}cccffffd........       int(*)[3]
    
    

提交回复
热议问题