萌新求问~我已经获取了元素个数给变量n,但是像下面这样却会报错,该怎么解决呢?
这种场景就不适合这么做;换成malloc或new吧;
编译器在编译时期对数组的检测要求其必须是已知长度的,你用变量设置,编译器怎么知道定义多大数组;
C++中给数组设定长度时只能使用整数或者宏定义的整数,即
#define A 3
int x[3];
int y[A];
使用变量和const常量都是不允许的
const int a=n;
int x[a]; //错误
如果你想用变量给数组设定长度,那么为什么不试试vector(向量,可变数组)呢
#include<vector>
int n=3;
vector<int> vec(n); //此时ver[0],[1],[2]都赋初值0
cout<<vec[2];//输出vec[2]