C++ question ; | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

C++ question ;

In the following code , why should we use dynamic memory allocation with new ? We know the “length” in advance, so why not using a normal array with the size of “length” ? is there any difference ?! Help plz 🙏🏻 #include <iostream> using namespace std; int main() { int length, sum = 0; cout << "Enter the number of students in the group" << endl; cin >> length; int *marks = new int[length]; cout << "Enter the marks of the students" << endl; for( int i = 0; i < length; i++ ) // entering marks of students { cin >> *(marks+i); } for( int i = 0; i < length; i++ ) // calculating sum { sum += *(marks+i); } cout << "sum is " << sum << endl; return 0; }

5th Jun 2020, 11:59 AM
Ali Hosseinzadeh
Ali Hosseinzadeh - avatar
4 Answers
+ 3
Without the use of `new` operator, you would be creating a Variable Length Array (VLA). https://en.m.wikipedia.org/wiki/Variable-length_array A VLA is created on the stack, which was not meant for large memory reservation or memory reservation where size needed is unknown until run-time. Also VLA is not part of the standard, meaning it may or may not be supported (depends on compiler). An advanced coder might suggest you to study the use of smart pointer. A kind of data structure which is smart in that it does a clean-up chores in the event of error (regular heap-based arrays don't). https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard Hth, cmiiw
5th Jun 2020, 12:42 PM
Ipang
+ 3
thank u both 🙏🏻
5th Jun 2020, 1:34 PM
Ali Hosseinzadeh
Ali Hosseinzadeh - avatar
+ 3
I think they are same is it?
5th Jun 2020, 2:00 PM
Naveed
Naveed - avatar
+ 2
i think this is because if u want to create an array in stack, the size need to be constant.. since the size is determined at runtime, the array is created in heap using the new keyword
5th Jun 2020, 12:29 PM
durian
durian - avatar