C++ array size dependent on function parameter causes compile errors

后端 未结 7 1788
甜味超标
甜味超标 2020-12-03 14:10

I have a simple function in which an array is declared with size depending on the parameter which is int.

    void f(int n){
        char a[n];
    };

    i         


        
7条回答
  •  伪装坚强ぢ
    2020-12-03 14:49

    You can use new/delete to allocate/free memory on the heap. This is slower and possibly more error prone than using char[n], but it's not part of the C++ standard yet, sadly.

    You can used boost's scoped array class for an exception-safe method for using new[]. delete[] is automatically called on a when it goes out of scope.

    void f(int n) {
        boost::scoped_array a(new char[n]);
    
        /* Code here. */
    }
    

    You can also use std::vector, and reserve() some bytes:

    void f(int n) {
        std::vector a;
        a.resize(n);
    
        /* Code here. */
    }
    

    If you do want to use char[n], compile as C99 code instead of C++ code.

    If you absolutely must allocate data on the stack for some reason, use _alloca or _malloca/_freea, which are extensions provided by MSVC libs and such.

提交回复
热议问题