How do I declare MULTIPLE 2d arrays in C using new

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

There is a similar topic about this. http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new

What I want to do is to create multiple 2d arrays according to some integer which determines how many 2d arrays there should be.

I want to create a single dimensional array first for pointers and assing every pointer to a multidimensional array, using new. But it seems like you can t ask for memory to create multidimensional array. Why can t we just write:

int** howManyPointers = new int*[translate];
for (int i = 0; i < translate; i++){
        howManyPointers[i] = new char[rowsUsed][2000];
    }

In my project, 2d array must have 2000 columns but row size is undetermined first. It will be given by the user. Assume you ve already got it [rowsUsed]

So what?

Answers

You allocate array of pointers, and then for each pointer you allocate 1d array like this:

int** 2dArray = new int*[rows];
for (int i = 0; i < rows; ++i) {
    2dArray[i] = new int[cols];
}

and then you can do 2dArray[X][Y] for each X < rows and Y < cols;

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/33321113/how-do-i-declare-multiple-2d-arrays-in-c-using-new

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils