int foo1()
{
int n;
cout<<"Enter the number of element\n";
cin>>n;
int *ptr = new int[n];
cout<<"Enter the elements:"<<endl;
for(int i=0; i<n; i++)
{
cin>>ptr[i];
}
cout<<"You entered : ";
for(int i=0; i<n; i++)
{
cout<<ptr[i]<<" ";
}
return 0;
}
int foo2()
{
int n;
cout<<"Enter the number of element\n";
cin>>n;
int arr[n];
cout<<"Enter the elements:"<<endl;
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"You entered : ";
for(int i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
Both foo1()
and foo2()
produces the same output. In foo1()
, I have used a dynamically allocated array, whereas in foo2()
I have used a regular array.
I know dynamically allocated arrays are used when the size of the array is unknown at compile-time.
If we can get the same result from regular arrays, why do use dynamically allocated arrays? Is there something wrong that I am doing in foo2()
which is not good practice?