semantic error:variable_sized object may not be initialized.

why?? I already set "n" as a const number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//copy int vector to int array
#include <iostream>
#include <vector>
#include <cstddef>
using namespace std;
int main()
{
    vector<int> ivec(5,2);
    const unsigned n=ivec.size();
    int iarr[n]={};
    size_t i=0;
    for(auto j:ivec)
    {
        iarr[i]=j;
        cout<<iarr[i]<<" ";
        i++;
    }
}
Line 9 means that you aren't going to change n after you have set it, not that it's a compile-time constant. Which makes line 10 try to set a VLA (variable-length array). Which doesn't conform to the C++ standard (although some compilers accept it).

Try
int *iarr = new int[n]{};
Got it! Thanks..
Topic archived. No new replies allowed.