My first thought was

int size = 0;
 cout << "Enter size of the array" << endl;
 cin >> size;
 int a[size];

Now I know that an array has to have a constant value, but I need that the user enters an integer and use that integer as the size of the array. Any idea how?

Recommended Answers

G++ and all C compilers support it. But it is not C++ standard so use what gerard4143 said.

int size;
cin >> size;
int *array = new int[size];

You can now treat it almost like a real array with indexing.

Jump to Post

All 4 Replies

You could create a dynamic array with the operator new.

int * a = new int[size];

Ideally you would use the std::vector class instead of trying to manage dynamic memory and pointers.

G++ and all C compilers support it. But it is not C++ standard so use what gerard4143 said.

int size;
cin >> size;
int *array = new int[size];

You can now treat it almost like a real array with indexing.

Ideally you would use the std::vector class instead of trying to manage dynamic memory and pointers.

Yeah, the standards committee spent all that time creating the standard temple libraries maybe we should consider the vector.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.