Array size at run time without dynamic allocation is allowed?

前端 未结 8 1692
一个人的身影
一个人的身影 2020-11-22 02:08

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;
             


        
相关标签:
8条回答
  • 2020-11-22 02:24

    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 _alloca.

    0 讨论(0)
  • 2020-11-22 02:24

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

    0 讨论(0)
  • 2020-11-22 02:29

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

    0 讨论(0)
  • 2020-11-22 02:34

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 02:37

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

    0 讨论(0)
  • 2020-11-22 02:39

    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.)

    0 讨论(0)
提交回复
热议问题