Array[n] vs Array[10] - Initializing array with variable vs real number

后端 未结 1 1089
清歌不尽
清歌不尽 2020-11-22 14:59

I am having the following issue with my code:

int n = 10;
double tenorData[n]   =   {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Returns the following

1条回答
  •  北海茫月
    2020-11-22 15:47

    In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

    int n = 10;
    double a[n]; // Legal in g++ (with extensions), illegal in proper C++
    

    If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

    int n = 10;
    double* a = new double[n]; // Don't forget to delete [] a; when you're done!
    

    Or, better yet, use a standard container:

    int n = 10;
    std::vector a(n); // Don't forget to #include 
    

    If you still want a proper array, you can use a constant, not a variable, when creating it:

    const int n = 10;
    double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
    

    Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

    constexpr int n()
    {
        return 10;
    }
    
    double a[n()]; // n() is a compile time constant expression
    

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