How would I go about dynamically allocating a multi-dimensional array?
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous. So the elements in multidimensional arrays can be stored in linear storage using two methods i.e., row-major order or column-major order.
In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];
If char charArray[50]; is defined at file scope (outside of all functions) or is static , it's not going to be on the stack, it's going to be a global preallocated at program's start variable. If it's not static and is defined at function scope, it's going to be on the stack.
A multidimensional array is declared using the following syntax: type array_name[d1][d2][d3][d4]……… [dn]; Where each d is a dimension, and dn is the size of final dimension.
If you know the size of nested dimensions already, you can also literally allocate a multi dimensional array using new:
typedef int dimensions[3][4]; dimensions * dim = new dimensions[10]; dim[/* from 0 to 9 */][/* from 0 to 2 */][/* from 0 to 3 */] = 42; delete [] dim;
instead of 10
, a runtime determined value can be passed. Since it's not part of the type operator new returns, that's allowed. This is nice if you know the number of columns, but want to keep the number of rows variable, for example. The typedef makes it easier to read the code.
For the sake of completeness, here is a better way to do it in C++ when you know the array bounds ahead of time. The benefit of using the following class is that you don't have to care about calling delete[] on your data. This means that this class will be exception-safe, and all of the other great stuff about RAII.
template<typename T, int width, int height> class MultiArray { private: typedef T cols[height]; cols * data; public: T& operator() (int x, int y) { return data[x][y]; } MultiArray() { data = new cols[width]; } ~MultiArray() { delete [] data; } };
Usage:
MultiArray<int, 10, 10> myArray; myArray(2, 3) = 4; cout << myArray(2, 3);
edit: and, while I'm at it, here is the setup you can use if you don't know the array bounds until runtime:
template<typename T> class Array2D { private: const int width; T * data; public: T& operator() (int x, int y) { return data[y*width + x]; } Array2D(const int w, const int h) : width(w) { data = new T[w*h]; } ~Array2D() { delete [] data; } };
Usage:
Array2D myArray(10, 10); myArray(3, 4) = 42; cout << myArray(3, 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With