views:

116

answers:

4
int *x = new int[5]();

With the above mentality, how should the code be written for a 2-dimensional array - int[][]?

int **x = new int[5][5] () //cannot convert from 'int (*)[5]' to 'int **'

In the first statement I can use:

x[0]= 1;

But the second is more complex and I could not figure it out. Should I use something like:

x[0][1] = 1;

Or, calculate the real position then get the value for the fourth row and column 1

x[4*5+1] = 1;
+2  A: 

You can do the initializations separately:

int **x = new int*[5];
for(unsigned int i = 0; i < 5; i++)
    x[i] = new int[5];
Michael Mrozek
That's what i want :)
jack london
+2  A: 

There is no new[][] operator in C++. You will first have to allocate an array of pointers to int:

int **x = new int*[5];

Then iterate over that array. For each element, allocate an array of ints:

for (std::size_t i = 0; i < 5; ++i)
    x[i] = new int[5];

Of course, this means you will have to do the inverse when deallocating: delete[] each element, then delete[] the larger array as a whole.

Jon Reid
+3  A: 

I prefer doing it this way:

int *i = new int[5*5];

and then I just index the array by 5 * row + col.

Simon
Very nice, this avoids the inefficiency of multiple allocations. You can wrap this in a class that hides things by doing the index calculation for you.
Jon Reid
...and then you can arrive to the solution from C++ FAQ Lite: http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.10
Cubbi
I agree, wrapping it in a class in order to do row/col access is very nice.
Simon
A: 

if the array has predefined size you can write simply:

int x[5][5];

It compiles

if not why not to use a vector?

kuszi
yes, the array is not static-sized. Just learning core elements. Like you mentioned the effective way is with stl.
jack london