Array-size defining

I think this method of defining a size of an array is wrong, but I have no idea why... Someone explain to me why this is wrong and explain a method of defining size of an array please. I am a beginner.
1
2
3
4
int n;
int array[n];
for (int i=0; i<n; i++) 
  cin >> a[i];
Try answering these:

What is the value of n on line 2?

Who needs to know the size? When?
what is an array? :)
keskiverto I forgot
cin >> n;
Anyone can know the size doesn't matter, and what do you mean by when?
Yes it is wrong, you need to initialize n before you try to use it.

Second since you're using C++ array sizes must be compile time constants.

I fixed my mistake, here is the code
1
2
3
4
5
int n;
cin >> n;
int array[n];
for (int i=0; i<n; i++) 
  cin >> array[i];

And what exactly do you mean by "since you're using C++ array sizes must be compile time constants." ?
How is the compiler to know how many ints to allocate if n is not known until runtime?

Use this instead:
 
  int *array = new int[n];


Don't forget to deallocate array.

edit: C99 does allow variable array allocation, but not C++.
Last edited on
Topic archived. No new replies allowed.