1

My textbook states that "The advantage of dynamic allocation is that it is not necessary to know the size of the array at compile time." And they give this example:

cout << "how many entries?";
cin >> numEntries;
double * dPtr = new double[numEntries];

cout << "Enter your values.\n";
for (int i = 0; i < numEntries; i++) {
    cin >> dPtr[i];
}

However I rewrote this code with static allocation and it works exactly the same way AFAIK:

int numEntries;
cout << "How many entries? ";
cin >> numEntries;
double arr[numEntries];
    
cout << "Enter your values.\n";
for (int i = 0; i < numEntries; i++) {
    cin >> arr[i];
}

So, what were they trying to say?

EDIT: I'm using gcc version 8.1.0

  • 4
    It only works on your compiler that implements non-standard C++ extensions. Try it on another compiler and see it fail. or try to allocate an array like that with about ten or so million values and watch your program crash. – Sam Varshavchik Feb 01 '21 at 13:07
  • 2
    [Variable Length Array (VLA) in C++ compilers](https://stackoverflow.com/q/39334435) – 001 Feb 01 '21 at 13:09
  • Although in standard C++ compilers it is not possible to have static array with dynamic size, it is still possible to emulate same behaviour using [alloca()](https://man7.org/linux/man-pages/man3/alloca.3.html) function which allocates memory on stack. It is non-standard function, different compilers have different headers/names for it (`alloca()` for GCC, `_malloca()` for MSVC, etc). I made example of usage [here by this link](https://cutt.ly/ukoecgF). Also notice that you DON'T need to call free() on alloca-pointer, stack is freed automatically. Also stack is not too large, limit array size. – Arty Feb 01 '21 at 13:34

0 Answers0