# Array error, this ain't possible?

## Recommended Posts

Hey all, I am programming a simple program, which asks you how many values you want to enter ( and ofcourse, you can enter those values later in the program ). I was thinking about using arrays. This is what I have programmed so far:
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
int x = 0;
cout<<"Enter how many values you want to enter: ";
cin>> x;

int variable_array[x];

for ( int y = 0; y <= x; y++ )
{
cout<<"Give me a value: ";
cin>> variable_array[y];
}

return 0;
}

Now it gives me those errors: 1>c:\documents and settings\vinnie the gamer\mijn documenten\visual studio 2005\projects\arrays\arrays\c++ file.cpp(13) : error C2057: expected constant expression 1>c:\documents and settings\vinnie the gamer\mijn documenten\visual studio 2005\projects\arrays\arrays\c++ file.cpp(13) : error C2466: cannot allocate an array of constant size 0 1>c:\documents and settings\vinnie the gamer\mijn documenten\visual studio 2005\projects\arrays\arrays\c++ file.cpp(13) : error C2133: 'variable_array' : unknown size Does anyone know what I am doing wrong? Greetings, Vinnie.

##### Share on other sites
An array's length must be constant; you cannot have an array of length x. If you want to create something like that, you might want to look at vector from the Standard Template Library.

##### Share on other sites
You can't use "int variable_array[x];" You'll have to use dynamic memory:

int *variable_array = new int[x];

##### Share on other sites
Quote:
 Original post by programwizardAn array's length must be constant; you cannot have an array of length x. If you want to create something like that, you might want to look at vector from the Standard Template Library.

Ah, so it ain't possible =( Well, guess I expected too much then :)

Thank you ;)

##### Share on other sites
Yes you should use a vector. Basicly vectors are defined as dynamic arrays, meaning they can get larger and smaller when needed. I personally never use arrays when I can avoid it and instead prefer vectors.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627734
• Total Posts
2978846

• 10
• 10
• 21
• 14
• 12