954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Variable size of an array

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?

GeorgeGVD
Newbie Poster
19 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

You could create a dynamic array with the operator new.

int * a = new int[size];
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

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

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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.

sergent
Posting Pro
598 posts since Apr 2011
Reputation Points: 70
Solved Threads: 22
 
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.

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: