I'm new to C++ and this is a very basic question.
In C++ there are only two ways to create dynamic arrays (read in a book, correct me if I'm wrong) using memory allocation either by new
operator or malloc()
function which is taken from C.
When declaring an array int array[size]
, the square brackets []
must have a const
.
However in the following code size
is an unsigned int
variable.
#include<iostream>
int main() {
using namespace std;
unsigned int size;
cout<<"Enter size of the array : ";
cin>>size;
int array[size]; // Dynamically Allocating Memory
cout<<"\nEnter the elements of the array\n";
// Reading Elements
for (int i = 0; i < size; i++) {
cout<<" :";
cin>>array[i];
}
// Displaying Elements
cout<<"\nThere are total "<<size<<" elements, as listed below.";
for (int j = 0; j < size; j++) {
cout<<endl<<array[j];
}
return 0;
}
While compiling g++ throws no error and moreover the program runs perfectly.
Question 1 : Could this be another way to create dynamic array?
Question 2 : Is the code correct?
Question 3 : If []
can only contain const
, why does the code work?