Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a 2D array with variable sized dimensions

Tags:

c++

arrays

I want to be able to create a 2d array the size of the width and height I read from a file, but I get errors when I say:

int array[0][0]
array = new int[width][height]
like image 236
CyanPrime Avatar asked Apr 01 '11 01:04

CyanPrime


2 Answers

You should use pointer to pointers :

int** array;
array = new int*[width];
for (int i = 0;i<width;i++)
    array[i] = new int[height];

and when you finish using it or you want to resize, you should free the allocated memory like this :

for (int i = 0;i<width;i++)
    delete[] array[i];
delete[] array;

To understand and be able to read more complex types, this link may be useful :

http://www.unixwiz.net/techtips/reading-cdecl.html

Hope that's Helpful.

like image 164
Tamer Shlash Avatar answered Oct 24 '22 03:10

Tamer Shlash


If the array is rectangular, as in your example, you can do it with just one allocation:

int* array = new int[width * height];

This effectively flattens the array into a single dimension, and it's much faster.

Of course, this being C++, why don't you use std::vector<std::vector<int> >?

like image 39
Jon Avatar answered Oct 24 '22 02:10

Jon