0

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?
6
  • 10
    You think wrong - we ALWAYS need to see the error messages! Commented Feb 11, 2010 at 23:40
  • 1
    This should work just fine (in the right context). What are the errors? Commented Feb 11, 2010 at 23:41
  • 2
    When you ask a question about a code that produces a compiler error, it is always a good idea to include the compiler error, even though it might be an easy task. If not for clarity of the problem, then for helping others attempting to find the answer to the problem later on. Besides in programming when only showing small snippets of code, it can very well be that the error is outside the shown code. Commented Feb 11, 2010 at 23:41
  • This will not spew any compiler errors, unless there's something wrong with the context. Any you are not sayng anything about the context. Commented Feb 11, 2010 at 23:44
  • 2
    give us either a complete code that produces the error, or the error itself ... both of them it's even better :) Commented Feb 11, 2010 at 23:45

2 Answers 2

14

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, fancy pants going for the clairvoyant badge. :)
2

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.

1 Comment

Turns out you needed to see the rest of the source.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.