Is it bad practice to use multi-dimensional arrays in C/C++?

前端 未结 9 901
北海茫月
北海茫月 2021-02-07 04:46

Some programmers seem to violently hate them, while others seem to think they\'re fine. I know that anything that can be done to a multi-dimensional array can also be done to a

9条回答
  •  长发绾君心
    2021-02-07 05:26

    Do you need to store multi-dimensional data where you know the dimensions ahead of time? If so, use a multi-dimensional array.

    If you don't know the dimensions ahead of time (i.e., you're going to have to dynamically allocate the array), then you either need to either

    • allocate a one-dimensional array and emulate an n-dimensional array using index arithmetic, or
    • allocate an array of pointers to arrays of elements to get actual multidimensional array semantics

    It depends on the specific use case, but as a rule of thumb, I almost always prefer the former because it makes for less memory management hassle and fewer heap allocations. The complexity for both approaches grows as the number of dimensions increases, but, in my opinion, it grows much faster for the latter approach due to the extra levels of indirection.

提交回复
热议问题