Mark Stroeven
Mark Stroeven

Reputation: 696

Initializing a multi dimensional array in C++

I recently started programming in C++, I have quite some experience in JAVA programming but I am facing a rather unclear situations whilst trying to initialize multi dimensional arrays in c++.

The code I would use in java would be something like:

int x = 5;
int y = 10;

int array [][] = new int[x][y];

which works fine, I could assign any value to x and y using a scanner or option pane. However (and please bear with me, I am quite new to c++) in c++ I am required to use constants which prevent me from using for example:

int x;
cin >> x;
int y;
cin >> y;
int array [][] = new int[x][y];

I am trying to make a random map generator, eventually i will assign 3d object to positions within the array and design an algorithm to sort all of the objects. However I want the user to be able to specify the size of the grid, specify x and y, the rows and columns.

Any help would be greatly appreciated!

Many thanks in advance.

Upvotes: 0

Views: 350

Answers (3)

Javier Mr
Javier Mr

Reputation: 2200

The dimensions of the array must be known at compile time.

For me this simple code fails to compile due to lack of knowledge of the array size.

int i = 5;

int arr [] = new int[i];

arr[2] = 2;

If you want to use arrays you have two choices, use constants that are known at compile time, or create the array using malloc to reserve memory.

If you are able to use the STL use the vector class.

int i = 5;

vector<int> vec(i);

vec[2] = 2;

Or you could use pointers as shown in 'Vlad from Moscow' or 'user3482801' answers.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

This record

int array [][] = new int[x][y];

is invalid in C++. If you want to allocate an array in the heap using operator new and the right dimension is not a constant expression then you should write

int x;
cin >> x;
int y;
cin >> y;

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

for ( int i = 0; i < x; i++ ) array[i] = new int[y];

If the right dimension is set by a constant expression then you can write

int x;
cin >> x;
const int y = SomeValue;

int ( *array )[y] = new int [x][y];

Take into account that you could use standard container std::vector instead of a manually allocated array.

For example

std::vector<std::vector<int>> v( x, std::vector<int>( y ) );

Upvotes: 2

Straw1239
Straw1239

Reputation: 689

There are multiple ways to do this. To create a permanent array on the heap:

int** data = new int*[x];
for(int i = 0; i < x;i++)
{
    data[i] = new int[y];
}

To create an array of fixed size on the stack:

int data[5][5];

Upvotes: 1

Related Questions