user2829334
user2829334

Reputation: 11

How to make an array that has a variable as the size?

For example:

int size;
cout << "Enter array size" <<endl;
cin >> size;
int myarray[size];

I want the user to be able to enter the size of the array, but I keep getting an error message saying I'm not using a constant variable. When ever I search for an answer to this question, I get information about how to store a variable in an array (not what I'm looking for).

Upvotes: 1

Views: 200

Answers (3)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158449

Variable length arrays are not part of the C++ standard, although they are part of the C99 standard and several compilers support them as an extension in C++ including gcc and clang, Visual Studio being one of the notable exceptions though.

The obvious C++ solution would be to use std::vector or possibly new although that means you have to worry about delete'ing the memory as well.

Upvotes: 4

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

In C++ you can simply use std::vector, in your case a std::vector<int>.

You then need to include the <vector> header.

using std::vector;
int size;
cout << "Enter array size ";
cin >> size;
vector<int> myarray(size);

A std::vector takes care of managing memory for you, and it also has a handy push_back method to add an item at the end, expanding the array as necessary.

This means that you do not have to decide up-front on a specific size, but can simply add more items.

Upvotes: 3

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275220

The proper way to handles this in C++03 and C++11 is to use a managed dynamic array type such as std::vector:

int size;
std::cout << "Enter array size" << std::endl;
std::cin >> size;
std::vector<int> myarray;
myarray.resize(size);

std::vector<int> behaves a lot like a raw array of ints. You can use [3] to access elements, as an example.

This is superior to managing the memory yourself, as ever experienced programmers lose track of memory.

There are proposals to add dynamically sized arrays to C++1y (the next iteration of C++) or later in an extension in a way that is somewhat compatible with C99 (an important difference is that sizeof(variable length array) in C99 is runtime evaluated, but not in C++). There are also proposals to add std::dynarray, which is a slightly less heavyweight std::vector style class with some possibility of automatic storage optimization. None of this is really needed to solve your problem.

Upvotes: 2

Related Questions