下面是我的(工作)代码:
#include <stdio.h>
int main(){
int fb=10;/*fold before 10th, starts from 0*/
int ln[9];
int at=fb-1; /*fold at this index, starts from nought*/
int sl=1;/*should loop, 1=yes, 0=no*/
while (sl==1){
for (int i=fb-2; i>=at;--i){
ln[i-at]=ln[i];
}
for (int i=fb-1-at;i<fb-1;i++){
ln[i]=getchar();
if (ln[i]=='E'){
sl=0;
break;
}
}
if (sl==0)
break;
at=fb-1;
for (int i=fb-2;i>=0;--i){
if (ln[i]!=' ' && ln[i]!=' '){
at=i+1;
break;
}
}
if (at==0)
at= fb-1;
for (int i=0;i<at;i++){
putchar(ln[i]);
}
putchar('\n');
}
return 0;
}在main 'int ln9‘开始工作,但是’intInfb-1‘不能工作:我得到了这个编译器错误注意:这是C,而不是C++。
使用#define 10也不起作用,我得到的错误基于不默认为int。
如何获得基于fb的数组大小?
发布于 2022-01-23 04:51:46
您所要求的是一个可变长度数组,这种数组在MSVC中是不支持的,尽管它们在gcc中是支持的。
如果您一直使用MSVC,那么唯一的选择就是动态地分配内存。
int *ln = malloc((fb-1) * sizeof *ln);一定要在使用完这个内存后调用free。
发布于 2022-01-23 04:47:54
C++编译器需要知道在编译期间要分配多少内存,但是,当数组的大小是一个变量时,直到运行时才知道数组的大小。因此,C++ (或C)不允许可变大小的数组。
如果要动态更改容器的大小,请使用std::vector,
http://www.cplusplus.com/reference/vector/vector/
一个例子是:
int n = 5;
std::vector<int> vec(n);https://stackoverflow.com/questions/70819159
复制相似问题