pointer - two dimensional array c++ exercises




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

I know that anything that can be done to a multi-dimensional array can also be done to a regular array

I do not think that's entirely accurate. We'll need an array of pointers to store something as basic as a list of names and then sorting it. Or pointers to pointers to store a variable length string and then a list of such strings. As the original questions mentions only arrays per se, can't see how problems like these can be done with equal ease in a regular array. Please consider not just storing the strings in a 1-D array (using some sort of separator maybe) but also performing operations such as sorting.

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?


Advantages of multi-dim arrays to Vector<Vector<>>

  1. Easy to type [ ][ ]
  2. C compatible.
  3. Simple to understand conceptually what is it is doing.

Disadvantages:

  1. No easily detected bounds checking. Bounding off the end of the outer brackets usually overflows into memory allocated by the inner brackets making these types of error a real pain to track.
  2. Jagged arrays require care to set up. Vector pattern is easy.
  3. 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.

Basically though, it comes down to lack of bounds checking for me.




It may be possible to store multi-dimensional data in a single-data array, but you have to keep track of the indexes yourself. Multi-dimensional arrays are actually stored in memory as a single dimensional array, with syntax to support representing that data as multi-dimensional.

If you are working with multi-dimensional data, then I feel it is most appropriate to choose the correct tool for the job (a multi-dimensional array).


There are following advantages of multi-dimensional arrays over Vector<Vector<>>:

  • They are easy to understand.
  • Searching and sorting of elements can be done very easily.
  • They are compatible with C.
  • They are easy to type.




multidimensional-array