dumb question (arrays in c++)

Started by
5 comments, last by CJWR 18 years, 9 months ago
what the heck am i doing wrong here?

int test[3];
test[0] = 1;
error messages: error C2466: cannot allocate an array of constant size 0 error C2501: 'test' : missing storage-class or type specifiers error C2086: 'test' : redefinition error C2440: 'initializing' : cannot convert from 'const int' to 'int []' i know it is these 2 lines of code, i just can't seem to figure out what i'm doing wrong with this... thank you for pointing out what i did wrong.
Charles Reed, CEO of CJWR Software LLC
Advertisement
It must be in another part of your program, because the following compiles fine for me:
int main() {  int test[3];  test[0] = 1;}

Based on what you posted, I'd say you have another variable named test in that same function. In cases like this, it helps immensly to post all of the code.
Just to make sure, what other lines are in that function? Those two lines by themselves should be legal...
Its not those 2 lines of code, is somewhere before those, perhaps one containing "int test[0];"
..
Judging from the error messages, I would say that those two lines are globally scoped. You cannot assign values in the global namespace. When the compiler sees "test[0] = 1" it thinks you're declaring a new array called "test" of unknown type, with a size of "0" and trying to assign the constant "1" to it. Hence the four error messages you're getting.

If you want to initialize your array with constant values, you could do something like:

int test[3] = {1,0,0};


For the array of constant size zero you may be initializing an array on the stack somewhere that does not use a constant(either a const variable or just a numeric value) as the array size. It doesn't look like it's the code you've posted as others have said.
error #2 should be because there was a problem when making test, and error 3 should be because of the place you define test earlier in your code, probably where the non-const array size is given.
I'm not exactly sure about error 4 without more code I guess.

Like the poster above me said, error 4 is probably where you define the const int '1' to the array that it thinks you're initializing, but I'm not sure really.
Quote:Original post by pragma Fury
..
Judging from the error messages, I would say that those two lines are globally scoped. You cannot assign values in the global namespace. When the compiler sees "test[0] = 1" it thinks you're declaring a new array called "test" of unknown type, with a size of "0" and trying to assign the constant "1" to it. Hence the four error messages you're getting.

If you want to initialize your array with constant values, you could do something like:

int test[3] = {1,0,0};


ah! thats it! thank you. i always thought you could assign values in global. i guess you learn something new everyday. thanks all.
Charles Reed, CEO of CJWR Software LLC

This topic is closed to new replies.

Advertisement