What's the difference between arrays of arrays and multidimensional arrays?

前端 未结 5 758
无人及你
无人及你 2020-12-20 17:34

I had a language-agnostic discussion with someone in the C++ chat and he said that arrays of arrays and multidimensional arrays are two things.

But from what I lear

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-20 18:11

    I get his point. He actually differ them from implementation point of view, but both are actually valid to be said multidimensional arrays.

    The "array of array" kind uses linear indexing as it's actually implemented as one dimensional array, despite at language level it's referenced via multiple index. Ex, in C:

    int a[5][5];
    

    would actually have the same structure as:

    int a[25];
    

    The compiler would translate an access such as:

    a[i][j]
    

    to:

    a[i * jDimensionWidth + j]
    

    where jDimensionWidth = 5 in above example. And it's even possible to access it like:

    int* b = (int*) a;
    printf("%d\n",b[12] == a[2][2]); // should output 1
    

    The "multidimensional array" kind is implemented through Iliffe vector as he said, where the indexing can't be linearized because the address is not linear as well since the vector is typically implemented as heap object. This kind of multidimensional array doesn't fit the equation (for 2-dimensional array):

    addr(a[i + 1]) = addr(a[i]) + (a[i].width * sizeof(a[i][j].datatype))
    

    which is fulfilled by the "array of array" kind.

提交回复
热议问题