Possible Duplicate:
Multi-dimensional array and pointers in C++?
Hi, In 1D I can declare an array like,
int *image = new int[W*H];
But in 2D how can I declare an array?
int *image = new int[W][H]; -- is it wrong??
Possible Duplicate:
Multi-dimensional array and pointers in C++?
Hi, In 1D I can declare an array like,
int *image = new int[W*H];
But in 2D how can I declare an array?
int *image = new int[W][H]; -- is it wrong??
int *image = new int[W][H]; -- is it wrong??
It will NOT compile. You should compile your code first, to know the answer of your question.
I think you want to do this:
//memory allocation
int **image = new int*[W];
for(size_t i = 0 ; i < W ; i++ )
image[i] = new int[H];
//use it as
for(size_t i = 0 ; i < W ; i++ )
for(size_t j = 0 ; j < H ; j++ )
image[i][j] = some_value;
int value = image[20][30]; //get value at (20,30) assuming 20 < W and 30 < H
//memory deallocation
for(size_t i = 0 ; i < W ; i++ )
delete [] image[i];
delete [] image;
But then why do all these when you've std::vector
? You could use it which will do all these nasty thing itself. Here is how you should be using std::vector
:
std::vector<std::vector<int> > image(W, std::vector<int>(H));
for(size_t i = 0 ; i < W ; i++ )
for(size_t j = 0 ; j < H ; j++ )
image[i][j] = some_value;
int value = image[20][30]; //get value at (20,30) assuming 20 < W and 30 < H
Since this is a question about C++:
Do not use C-style arrays or pointers (neither for 1D nor 2D arrays). Use the C++ data types, such as vector
:
vector<int> image(W * H); // 1D array
vector<vector<int> > image(W, vector<int>(H)); // “2D” nested array.
This requires the vector
standard header.
int** image = new int*[H];
for(int i = 0; i < H; i++)
image[i] = new int[W];