Shiva Verma
Shiva Verma

Reputation: 89

array declaration in runtime and compile time

Please look at the following 2 program segments:

  int a,b; 
  cin>>a>>b;   
  int arr1[a*b];
  int arr2[a];

now if i give input value of 'a' = 100000 and 'b' = 5, program shows runtime error because of memory overflow I think. Now look to the other segment of code:

  int arr1[500000];
  int arr2[100000];

Now when I declare array of same size as shown in above code, The program works fine. Why is that so?

Upvotes: 1

Views: 1185

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Now when I declare array in advance of same size I declared at runtime, The program works fine. Why is that so?

Because variable length arrays (aka VLAs) aren't valid standard c++ code.

If you need such thing allocated at runtime the idiomatic c++ way is to use a std::vector:

int a,b; 
cin>>a>>b;   
std::vector<int> arr1(a*b);
std::vector<int> arr2(a);

Upvotes: 1

Related Questions