This post introduce methods of constructing and calling multidimensional array in C/C++.
The key point of mutlidimensional array is using the pointer to pointers. For example, constructing two dimensional array requires a pointer array, each element of which points to an one dimensional array.
C
A simple method is:
A simple method
1 | int** alloc_float2(int nx, int ny) { |
However, this is a bad design since both malloc and free are called for twice. More over, forgetting to free the data scope (p[0]
) often happens.
Better method
A better method is put the pointer array and data scope array together. Thus, operations of malloc and free are called for only once.
1 | int** alloc_f2(int nx, int ny){ |
C++
It is disaster for constructing multi-dimensional array in C because of lots of types, such as int
, float
, double
… We need to write codes repeatedly for these types. However, C++ provides a nice method for simplify these, TEMPLATE!
1 | template <class T> |
Elegant method
C++ provides class
for us to packaging everything. Why not using it?
1 | template <class T> |
Example above is the simplest design for two dimensional array. More advanced design is gsw.