arrays

I want to declare several different arrays, which are contained in several different functions. So what I want to do is something along these lines:
1
2
3
4
5
6
7
8
9
void funtionA(){
	const int numberOfElements = 6;
	int firstArray[numberOfElements];
	funtionB(numberOfElements);
}

void functionB(const int numberOfElements){
	int secondArray[numberOfElements];
}


in functionA declaring firstArray is OK because numberOfElements is constant. However in functionB I get the error "error: variable-sized object 'secondArray' may not be initialized"

What am I doing wrong?
Last edited on
I would say you know what you are doing wrong: In functionB(), numberOfElements is not known at compilation time, which is the requirement to declare arrays like this in the stack. You just can't do it like this. You need an STL container, or a dynamic C array in functionB().
Ah but in my situation the number of elements in each array is known at compile time. In the example above I could simply type in int firstArray[6] and int secondArray[6] but the two arrays need to have the same number of elements in them, so if someone is to change the size of the array (which is hardcoded) at a later date, then they should change the value of numberOfElements to avoid accidently changing one array but not the other array in the other function. It's pretty much just an attempt to avoid using what some people call "magic numbers".
Last edited on
Ok, then you are doing it wrong: Why do you declare the constant at the function level? Make it global, or at least available to both functions:

1
2
3
4
5
6
7
8
9
10
11
static const int numberOfElements = 6;

void functionA()
{
    int firstArray[numberOfElements];
}

void functionB()
{
    int secondArray[numberOfElements];
}
Topic archived. No new replies allowed.