0
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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    Add `-pedantic-errors` to your compiler options and watch the second block no longer compile. C++ has never supported `cin>>n; int arr[n];`, but gcc allows it by default as an extension. – NathanOliver Aug 13 '21 at 18:12
  • Because "regular arrays" is not standard C++. And good luck trying to figure out how to keep them around after the function returns. – Sam Varshavchik Aug 13 '21 at 18:12
  • In `foo2`, the `int arr[n];` is not good practice. VLA in C++ may be an extension in your C++ compiler, but it does not work in mine. It's not part of C++. – Eljay Aug 13 '21 at 18:12
  • `foo2` doesn't produce the same output for me when I use MSVC. For some discussion of [why](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) this decision was made, see this question. – Nathan Pierson Aug 13 '21 at 18:12
  • Variable Length Arrays (VLAs) are not part of *Standard* C++, although some compilers (notably g++) have them has an extension. – Adrian Mole Aug 13 '21 at 18:13
  • 1
    You should be using `std::vector arr(n);` instead. – Some programmer dude Aug 13 '21 at 18:14
  • Your instructor has failed you, OP. – sweenish Aug 13 '21 at 18:30
  • OK, so your compiler allows it, but think on what can happen with `cin>>n; int arr[n];` if the user types something like 10000000. How much stack space will you have left for other variables at that point? – user4581301 Aug 13 '21 at 18:41
  • As a side note, in `foo1` you've introduced a `memory leak`, there you have your reason for using `std::vector over arrays` – NRUB Aug 13 '21 at 19:19

0 Answers0