0

hello i am new to c++ programming. here are two methods of allocation of dynamic arrays and both give the same output. i want to know what is the difference between the two.

1)here is method 1 using new and delete :

#include<iostream>
using namespace std;

int main()
{
 int n;
 cout<<"enter the array size : ";
 cin>>n;
 int *arr = new int[n];              
 cout<<"enter the array elements: ";
 for(int i=0;i<n;i++)
    {
     cin>>arr[i];
    }
 cout<<"array elements are: ";
 for(int i=0;i<n;i++)
    {
     cout<<arr[i]<<" ";
    }   
 cout<<"\n";
 delete [] arr;
 return 0;                   
}

2)here is method two :

#include<iostream>
using namespace std;

int main()
{
 int n;
 cout<<"enter the array size : ";
 cin>>n;
 int arr[n];               
 cout<<"enter the array elements: ";
 for(int i=0;i<n;i++)
    {
     cin>>arr[i];
    }
 cout<<"array elements are: ";
 for(int i=0;i<n;i++)
    {
     cout<<arr[i]<<" ";
    }   
 cout<<"\n";                   
 return 0;
}
RXDG14
  • 23
  • 4
  • 2
    the difference is that the second is not valid C++ – 463035818_is_not_a_number Jan 24 '20 at 12:54
  • `int arr[n];` is not valid c++ see here: [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – drescherjm Jan 24 '20 at 12:55
  • 1
    btw prefer `std::vector` for dynamic arrays, they are easier to work with and less error prone. Also read about [why c++ programmers should minimize the use of `new`](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) – 463035818_is_not_a_number Jan 24 '20 at 12:55
  • If you *really, really* need data with dynamic size allocated on stack in C++, you might try [alloca](https://linux.die.net/man/3/alloca). Non-standard, though, but even available on Windows. By the way, I would have considered standardising that function far better than VLA (apart from in function signatures, where they are fine). – Aconcagua Jan 24 '20 at 18:12

0 Answers0