salute..
I am learning dynamic allocations for multidimensional arrays in a book and I found some ways for that, And now haven't problem in it. But the author of the book shows us a way, but it doesn't work correctly. It is this:
pbeans = new double [3][4]; // Allocate memory for a 3x4 array
And this is t开发者_StackOverflowhe error:
error C2440: '=' : cannot convert from 'int (*)[4]' to 'int *'
how should i define pbeans ( if this type of coding is legal)?
and what is the problem exactly?
Regards.
This is covered in my FAQ on arrays:
double (*pbeans)[4];
pbeans = new double[3][4];
// ...
delete[] pbeans;
For the "C declarator impaired", you could make that more readable with a typedef:
typedef double row[4];
row *pbeans;
pbeans = new row[3];
// ...
delete[] pbeans;
But in C++, we prefer RAII containers over raw pointers:
#include <vector>
#include <array>
std::vector<std::array<double, 4> > beans(3);
Note the complete absence of delete[]
which makes this solution exception-safe.
You need to allocate each dimension of the array separately:
double **pbeans = new double*[3];
for (int i = 0; i < 3; ++i) {
pbeans[i] = new double[4];
}
Here is a way to do it that allocates the memory contiguously on the heap:
typedef double MyGrid[3][4];
int main(int argc, char* argv[])
{
MyGrid& x = *(reinterpret_cast<Grid*>(new double[12]));
...
x[1][2] = 0.3333;
...
delete[] &x;
return 0;
}
Which you could easily turn into a more generic solution:
template<typename T, int x, int y>
struct Array2D
{
typedef T CArrayType[x][y];
typedef CArrayType& RefType;
static CArrayType& New()
{
return *(reinterpret_cast<CArrayType*>(new T[x * y]));
}
static void Delete(RefType x)
{
delete[] &x;
}
};
typedef Array2D<double, 3, 4> MyGrid;// define your 2d array with 3 rows / 4 columns.
int main(int argc, char* argv[])
{
MyGrid::RefType j = MyGrid::New();
...
j[1][2] = 0.3333;
...
MyGrid::Delete(j);
return 0;
}
The idea is to just generate the elements in 1D (x*y), and cast it to a 2D array. But since array types are value types, you need to deal in pointers-to-arrays. Using a reference makes it almost transparent.
Boost probably has something like this but I don't know boost well enough to say...
精彩评论