global variables and mulidimensional arrays outside of main in c++
EDIT #1 So I think my solution is to pass the class around through the functions, si then I have to get the size values in main and pass them into the class. So how would I create a multidimensional array within the class based on 2 int values? This is what I have, but I get the error "`ii' cannot appear in a constant-expression "
class tempHolder{
public:
bool C1[col1][row1];
tempHolder(){
}
tempHolder(int i, int ii){
int* C1 = new bool[i][ii];
}
}
So my program has a multidimensional array, but I'm using global variables (which I know is bad style) to declare the size of the array. The problem is that I also pass this array to functions and I use it in a class, like开发者_JAVA百科 the code below...
#include <iostream>
using namespace std;
const int row1 = 12;
const int col1 = 32;
class tempHolder{
public:
bool C1[col1][row1];
void operator=(bool C2[col1][row1]){
for(int i=0;i<row1;i++)
for(int ii=0;ii<col1;ii++)
C1[i][ii] = C2[i][ii];
}
};
void printTable(bool CC[][row1], int, bool);
int main(int argc, char *argv[]) {
col1=5; //error
bool C1[col1][row1];
So I want to be able to change the values of row1 and col1 right at the beginning of main, which would then change the array size for the entire program. If I declare the global variables like above, then the program compiles, but since they are constants, I won't be able to change them. I can't use a #define because those are not changeable at all. So what can I do to resize the array for the entire program?
You cannot simply change the size of the array by simply changing the dimensions at runtime - you need to allocate the memory dynamically with new. Best is usually to use the STL containers - they have their length property built in and can be easily resized.
The size of the arrays is set before main
begins, when the program is compiled.
So, even if col1
only changes once at startup, it still must be a proper non-const
variable.
You likely want std::vector
to implement a variable-sized array. Note that vector<bool>
is a specially-optimized class which uses one bit, not one byte, per Boolean value. You might try using vector<char>
instead if there are problems or performance is poor.
#include <iostream>
using namespace std;
int row1 = 12;
int col1 = 32;
typedef vector< vector< bool > > bit_array_2d;
class tempHolder{
public:
bit_array_2d C1;
void operator=( bit_array_2d const &C2 ){
C1 = C2;
}
};
int main(int argc, char *argv[]) {
col1=5; // OK
bit_array_2d C1( col1, vector< bool >( row1 ) );
A more advanced approach, if there are only a few potential sizes to select from, is to use template-parameterized C arrays.
精彩评论