简体   繁体   中英

Constant for a multi-dimensional array

I'm trying to create a multi-dimensional array, the size of which the user will supply.

So far I have this:

int definedgroups; // for number of groups needed

cout << "Enter the Number of Groups you require: " << endl;
cin >> definedgroups;
const int definedgroups = definedgroups;

int User_Groups [definedgroups] [4];

I believe the array needs constant values, so i tried assigning my variable as a constant but still no luck.

In C++, static arrays, that is, those defined like this:

foo arrayStatic[bar];

require bar to be a constant integer. In other words, the programmer needs to know its value beforehand.

Whenever bar is unknown, a dynamic array could be used instead. They're defined like this:

foo* arrayDynamic;
arrayDynamic = new foo[bar];

Here, bar could be an integer variable.

Don't forget that dynamic memory must be deallocated eventually. So, in this case, we can deallocate arrayDynamic like this:

delete [] arrayDynamic; 

A two-dimensional dynamic array is defined analogously:

foo** arrayDynamic2D;
arrayDynamic2D = new foo*[bar];
for (int i = 0; i < bar; i++)
   arrayDynamic2D[i] = new foo[baz];

and deallocated in a similar fashion:

for (int i = 0; i < bar; i++)
   delete [] arrayDynamic2D[i];
delete [] arrayDynamic2D;

Static memory is allocated in the stack whereas dynamic memory is allocated in the heap .

It's not possible to do it in C++ using static arrays. Use std::vector in a hierarchical way (ie vectors of vectors) to implement a multi-dimensional array easily (though not necessarily very efficiently).

Eg

std::vector<std::vector<double> > array(nrows, std::vector<double>(ncols));

creates a nrows x ncols matrix.

You need dynamic memory allocation using new :

int **User_Groups = new int*[definedgroups];
//Allocate memory for 2nd dimension
for (int i = 0; i < 4; ++i)
    User_Groups[i] = new int[4];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM