0

When I started programming with C++ I was learned to allocate the array size by using dynamic memory allocation as follows:

int main()
{
    int nArrayLength;

    cout << "Enter an array length: ";
    cin  >> nArrayLength;

    int *nArray = new int[nArrayLength];

    // contents

    delete[] nArray;

    return 0;
}

Now I tried the following code using Code::Blocks 12.11 with the mingw32-g++ // GNU GCC compiler.

int main()
{
    int nArrayLength;

    cout << "Enter an array length: ";
    cin  >> nArrayLength;

    int nArray[nArrayLength];

    return 0;
}

This also works fine.

Therefore, why should I use dynamic memory allocation in this case when the easier method also works fine?

Pietair
  • 396
  • 2
  • 8
  • 18

5 Answers5

7

You should use neither.

The first is valid, but it's C-style code. The second is non-standard code - it's accepted by that compiler because of some extension.

Use a std::vector instead:

#include <vector>
int main()
{
    int nArrayLength;

    cout << "Enter an array length: ";
    cin  >> nArrayLength;

    std::vector<int> nArray(nArrayLength);

    return 0;
}

A vector has the same semantics as an array, it can grow dynamically (and automatically), and does all the pesky memory management under the hood.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
3

The second code is not valid standard C++. It uses a compiler extension called variable length arrays. See the GCC documentation.

However, there is a proposal for variable length arrays with automatic storage duration that has been adopted for C++14.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
1

Compile the second code with -pedantic option if you're using GCC. It would not compile.

It is because it is not Standard conformant. Variable Length Array (VLA) is not in the Standard C++. It is a compiler extension.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

Sometimes you don't know the size of your array beforehand, so you need to allocate storage for it that may grow or shrink dynamically. You should use std::vector because it manages the array storage transparently.

If you are forced to use C-style arrays, use them like in the first code snippet, the second one is not standard C++.

Daniel Martín
  • 7,815
  • 1
  • 29
  • 34
0

It depends whether you want to use the stack or the heap.

You can also use auto_ptr if you want your heap allocation to be released automatically when scope goes out.

Ali Burak Kulakli
  • 562
  • 1
  • 5
  • 16