The old fashioned way of initializing a pointer to a pointer, is correctly enough with the new
operator, you would first initialize the the first array which is a pointer to doubles (double*
), then you would iterate through that allocating the next pointer to doubles (double*
).
double** pSamples = new double*[N];
for (int i = 0; i < N; ++i) {
pSambles[i] = new double[M];
}
The first new allocates an array of double pointers, each pointer is then assigned to the array of pointers allocated by the second new
.
That is the old way of doing it, remember to release the memory again at some point using the delete []
operator. However C++ provide a lot better management of sequential memory, such as a vector
which you can use as either a vector of vectors, or simply a single vector capable of holding the entire buffer.
If you go the vector of vector way, then you have a declaration like this:
vector<vector<double>> samples;
And you will be able to reference the elements using the .at
function as such: samples.at(2).at(0)
or using the array operator: samples[2][0]
.
Alternatively you could create a single vector
with enough storage to hold the multidimensional array by simply sizing it to be N * M
elements large. However this method is difficult to resize, and honestly you could have done that with new
as well: new double[N * M]
, however this would give you a double*
and not a double**
.