Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 regular array, so they're functionally equivalent. Is it bad practice to use multi-dimensional arrays, or does it not matter?

like image 255
Maulrus Avatar asked Apr 21 '10 02:04

Maulrus


People also ask

Are multidimensional arrays bad?

Multidimensioal arrays are more than double pointers making it a pain to pass into functions correctly. Most of the time, I've seen them just passed as a raw address to a double pointer which defeats the intrinsic math the compiler will do for you.

Can we use multi-dimensional array in C?

Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.

Are multidimensional arrays useful?

They are very useful if you need them. For example, you could be dealing with 3D objects (x,y,z) coordinates or for mathematical research.


1 Answers

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.

like image 111
James McNellis Avatar answered Sep 18 '22 17:09

James McNellis