-2

im a beginner in c++. i want to create multiple arrays with different size at run time. i tried the below codes which got compiled and ran. But it seems not right after comparing with other answers i googled. Mostly of the results say it should be done using new and delete or vector or some other library implementations. Can anyone help point out what is wrong with it?

void Basics::TestArray(int length){
      int arr[length];
      for(int i=0;i<length;i++){
          arr[i] = i;
      }
}
PublicAngus
  • 1
  • 1
  • 1
  • 5
    Possible duplicate of [How to create a dynamic array of integers](https://stackoverflow.com/questions/4029870/how-to-create-a-dynamic-array-of-integers) – Weak to Enuma Elish Sep 02 '17 at 07:15
  • 4
    use vector instead of array – Shubham Agrawal Sep 02 '17 at 07:16
  • thx for dropping comments. the link from @JamesRoot does give information on creating arrays which indeed sovled the question state in the question title, but not the additional problem why my supplied code works. Artemy 's answer below solved my confusion. – PublicAngus Sep 02 '17 at 07:43

2 Answers2

2

Variable length arrays (VLA) is feature of the C99. It is not supported by the standard C++. Some C++ compilers provide support of VLA as compiler extensions but I would stay away from it.

Best way to achieve the same in C++ - by using std::vector

std::vector<int> arr(length);
for(auto i=0;i<arr.size();i++){
      arr[i] = i;
}
Artemy Vysotsky
  • 2,694
  • 11
  • 20
0
void Basics::TestArray(int length){
  int *arr =new int[length];
  for(int i = 0; i < length; i++) {
      arr[i] = i;
  }
  //do something with your array before it gets deleted
  delete []arr;
}

I'm surprised your code compiled without an error because 'length' needs to be a constant in that code.

Above is a way that it can be done using a pointer to an array, but note that if you use the 'new' keyword, you have to delete the array or you will leak memory. (Because the array was created within the function, it has to be deleted before exiting the function as it will go out of scope and there will be no way to access it again.)

If you really want to use dynamic arrays in this way, I think it is better to create a wrapper class where it can be deleted automatically in the destructor when it goes out of scope. However, using the std::vector class as suggested above, is recommended.