2

I want to initialize an array with a size using a value I read into an integer variable. I cant seem to understand why it works in Dev-C++ but not in Turbo C++. Here's the code to help make things clear

int arr_size; //cin max value for lets say number of students or something...
cin >> arr_size;
int array[arr_size]; // declares array with size (assume 10 or 100) with range 0 to 9 or 0-99

The compiler shows an error in Turbo C++ (really old, I know, but my school uses it unfortunately). Dev-C++ and codeblocks doesnt.

Why is that so? I know its bad practice "as they define it in some books" to have an array size the same as an int value, but is there a work around for this in Turbo C++? I want to know why the error happens and how I can get a work around it ... thanks a lot!

Kijewski
  • 25,517
  • 12
  • 101
  • 143
Yogi Cplusplus
  • 23
  • 1
  • 2
  • 4
  • possible duplicate of [Dynamic array in Stack ?](http://stackoverflow.com/questions/1204521/dynamic-array-in-stack) – iammilind Jun 13 '11 at 12:59
  • Always thought variable length arrays are not allowed in standard c++. You can do it in C. See http://en.wikipedia.org/wiki/Variable-length_array – dubnde Jun 13 '11 at 13:00

4 Answers4

8

The C++ standard only permits arrays to be sized with a constant expression. (However, some compilers may offer it as a non-standard language extension.)

You could use a std::vector instead:

std::vector<int> array(arr_size);

Or you could dynamically-allocate memory manually:

int *const array = new int[arr_size];

...

delete [] array;  // Remember to delete when you're done
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
7

Variable length arrays are not allowed in standard c++. You can do it in C99. Consider using C++ std::vector as :

std::vector<int> array(arr_size);

And you can index it exactly like the array if you have to.

dubnde
  • 4,359
  • 9
  • 43
  • 63
2

The workaround is to dynamically allocate this array, making sure to delete the memory when done.

int arr_size; //cin max value for lets say number of students or something...
cin >> arr_size; 
int *arr = new int[arr_size];
//use the array as needed
delete [] arr;
Kik
  • 428
  • 3
  • 9
1

You want variable length array (VLA) which is not allowed in C++. Its allowed in C99.

Use std::vector<int> instead, as:

int arr_size; 
cin >> arr_size;
std::vector<int> array(arr_size);
Nawaz
  • 353,942
  • 115
  • 666
  • 851