How Pointer of Multi-Dimension Arrays Work in C

后端 未结 3 681
星月不相逢
星月不相逢 2020-12-10 08:40

I\'m experimenting with the concept of pointer to multi-dimension array in C. Suppose I want to process a multi-dimensional array via a function. The code kinda looks like t

3条回答
  •  误落风尘
    2020-12-10 09:25

    The problem is because int array[10][10] allocated on the stack does not lay out memory the way you think it does. This is because arrays are not pointers. The memory is still laid out in a linear array, not a "two dimensional" array, even though that's what the subscripts might indicate. In other words, the memory for int array[10][10] looks like the following:

    starting address:                                    ending address:
    | Block_1 of 10 int | Block_2 of 10 int | ... | Block_10 of 10 int |
    

    So when you implicitly convert the array to an int***, and then try to access the array like (*array)[1][10], what this actually translates to is something like *(*((*array) + 1) + 10), and the memory layout for such an operation wants to see memory setup like the following:

    int*** array
    |
    |
    | Pointer |
    |
    |
    | Pointer_0 | Pointer_1 | ... | Pointer 10 |
           |          |                 |
           |          |                 | Block of 10 int |
           |          |
           |          | Block of 10 int |
           |
           |Block of 10 int|
    

提交回复
热议问题