Performance of 2-dimensional array vs 1-dimensional array

后端 未结 6 1302
谎友^
谎友^ 2020-11-27 14:46

In C, is there a difference in time and space between an m×n 2-dimensional array vs a 1-dimensional array of length m×n (for large values of m and n)? Will accessing element

6条回答
  •  一向
    一向 (楼主)
    2020-11-27 15:24

    Actually, if you use the so-called two-dimensional array in C, the compiler will do the mapping into one-dimensional array for you. If you use one-dimensional array and you like to treat it as a two-dimensional one, then you have to write the mapping yourself.

    The only thing that you have to take care of is you should access the array row-wise, because the C compiler will store your two-dimensional array row after row. If you access a 'big' two-dimensional array column-wise then page-faults are likely to happen. Even if you are programming in language that supports only one-dimensional arrays, you could easily write the mapping into any number of dimensions.

    Take a look at this Wikipedia article if you want to do the mapping row-wise. Your mapping could be column-wise, like FORTRAN matrices for example.

提交回复
热议问题