tags:

views:

133

answers:

2

I've got some problems/misunderstandings with arrays in C++.

int myArray[30];
myArray[1]=2;
myArray[2]=4;

This is spitting out a lot of compiler errors. I don't think it is necessary to include them here as this is an easy question for everybody with experience in C(++) I guess

  • Why doesn't this work?
  • Is there a way to create a "dynamic" array that has a fixed ammount of values (so no malloc needed) but where I can change the values during runtime?
+14  A: 

I'm guessing you have that outside of a function.

You are allowed to define variables outside of a function. You can even call arbitrary code outside of a function provided it is part of a variable definition.

// legal outside of a function
int myArray[30];

int x = arbitrary_code();

void foo()
{

}

But you cannot have arbitrary statements or expressions outside of a function.

// ILLEGAL outside a function
myArray[1] = 5;

void foo()
{
    // But legal inside a function
    myArray[2] = 10;
}
R Samuel Klatchko
Oh, fancy pants going for the clairvoyant badge. :)
GMan
@GMan - you read my mind :-)
R Samuel Klatchko
+2  A: 

Are you saying that this doesn't compile:

int main() {
    int myArray[30];
    myArray[1]=2;
    myArray[2]=4;
}

If it doesn't, you have something wrong with your compiler setup. As I said in my comment, we need to see the error messages.

anon
Turns out you needed to see the rest of the source.
Mike D.