Array size at run time without dynamic allocation is allowed?

C++CArray Initialization

C++ Problem Overview


I've been using C++ for a few years, and today I saw some code, but how can this be perfectly legal?

int main(int argc, char **argv)
{
    size_t size;
    cin >> size;
    int array[size];
    for(size_t i = 0; i < size; i++)
    {
        array[i] = i;
        cout << i << endl;
    }

    return 0;
}

Compiled under GCC.

How can the size be determined at run-time without new or malloc?

Just to double check, I've googled some and all similar codes to mine are claimed to give storage size error.

Even Deitel's C++ How To Program p. 261 states under Common Programming Error 4.5:

> Only constants can be used to declare the size of automatic and static arrays.

Enlight me.

C++ Solutions


Solution 1 - C++

This is valid in C99.

C99 standard supports variable sized arrays on the stack. Probably your compiler has chosen to support this construct too.

Note that this is different from malloc and new. gcc allocates the array on the stack, just like it does with int array[100] by just adjusting the stack pointer. No heap allocation is done. It's pretty much like https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/alloca?view=vs-2019">`_alloca`</a>;.

Solution 2 - C++

This is known as VLAs (variable length arrays). It is standard in c99, but gcc allows it in c++ code as an extension. If you want it to reject the code, try experimenting with -std=standard, -ansi and -pedantic options.

Solution 3 - C++

It is valid only in C99. Next time you may try checking your code in a reliable compiler.

Solution 4 - C++

It is valid C99, it is not valid C++. This is one of not a few differences between the two languages.

Solution 5 - C++

This Code runs in GNU GCC Compiler.

#include<bits/stdc++.h>

int main(int argc, char **argv)

{
    size_t size;

   std:: cin >> size;

    int array[size];

    for(size_t i = 0; i < size; i++)
    
{
        
array[i] = i;

        std:: cout << i;
   
 }

    return 0;
}

Solution 6 - C++

You can give size to an array dynamically in if you are using Dev-Cpp compiler I have tried it and got no error but on visual c++ and visual studio compilers it is not possible. I think the reason is that dev-c++ assigns a positive number to the uninitialized int and when we give it a number it is replaced by the given one. but perhaps other compilers give null to uninitialized variables.

Solution 7 - C++

I recently came across a scenario where a stack-allocated array is desired. (It's a wrapper around v8, needed an array of args on every method call).

An std::vector would do heap memory allocation, whose performance is not acceptable.

Here is my solution, use template to allocation array of cases:

template<size_t Argc>
static void call(...) {
    v8::Local<v8::Value> v8Args[Argc];
    
    // use v8Args
    ...
}

template<typename It>
static void callV8Function(size_t argc, It argvBegin, It argvEnd,) {
    // C++ don't have dynamic stack allocation (like C99 does)
    // try to avoid heap-allocation...
    if (argc <= 4) {
        return callV8FunctionOnStack<4>(...);
    } else if (argc <= 8) {
        return callV8FunctionOnStack<8>(...);
    } else if (argc <= 16) {
        return callV8FunctionOnStack<16>(...);
    } else if (argc <= 32) {
        return callV8FunctionOnStack< 32>(...);
    } else {
        std::vector<v8::Local<v8::Value>> v8Args(argc);
        // fallback to vector
   }
}

(And of course, I can just do with a 32-sized array, but which is not so elegant.)

Solution 8 - C++

Variable Length Arrays (VLAs) are supported in the C++14 standard, which has recently been accepted, and is awaiting publication.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsyazView Question on Stackoverflow
Solution 1 - C++mmxView Answer on Stackoverflow
Solution 2 - C++jpalecekView Answer on Stackoverflow
Solution 3 - C++ÖzgürView Answer on Stackoverflow
Solution 4 - C++anonView Answer on Stackoverflow
Solution 5 - C++DungeonView Answer on Stackoverflow
Solution 6 - C++NajeebView Answer on Stackoverflow
Solution 7 - C++landerlyoungView Answer on Stackoverflow
Solution 8 - C++ElkvisView Answer on Stackoverflow