0

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??
Community
  • 1
  • 1
user570593
  • 3,420
  • 12
  • 56
  • 91
  • Nobody answered this correctly, here or at the duplicated question. I can't post my answer here, because this question is closed, but you can see it here: http://stackoverflow.com/questions/3367426/multi-dimensional-array-and-pointers-in-c/6226628#6226628. – TonyK Jun 03 '11 at 11:40
  • @TonyK Both Nawaz and me *did* in fact answer this question correctly. Your way also works but I find it needlessly complicated, and at any rate inferior to using proper C++ classes. – Konrad Rudolph Jun 03 '11 at 13:31
  • @Konrad: I suspect that your real objection to my answer is that it is needlessly simple. – TonyK Jun 03 '11 at 16:05
  • @TonyK Nothing of that sort. In fact, using vectors is vastly simpler. Now, what would your objection to *our* answers be? – Konrad Rudolph Jun 03 '11 at 20:03
  • @Konrad: You only have to look at Nawaz's answer to see that it's ten times more complicated than mine. Your answer is fine, except that it didn't answer the OP's question: "How do I do this?" "DO NOT DO THIS!" – TonyK Jun 03 '11 at 20:27

4 Answers4

3
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
Nawaz
  • 353,942
  • 115
  • 666
  • 851
3

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2
int** image = new int*[H];
for(int i = 0; i < H; i++)
    image[i] = new int[W];
Farshid Zaker
  • 1,960
  • 2
  • 22
  • 39
-2

I use something like

int ** image....
Aslan986
  • 9,984
  • 11
  • 44
  • 75