大家早上好。我试图用用户输入的元素填充一个数组;问题是虽然我已经在互联网上找到了这个问题的答案,但它说我的代码应该可以工作,但事实并非如此。具体来说,电脑说程序在我尝试运行后停止工作,老实说我真的不明白我哪里错了。代码如下:
#include <iostream>
using namespace std;
void getarray (int[],int);
void print (int[],int);
int main(){
const int size=10;
int n[]={0};
getarray (n,size);
print (n,size);
}
void getarray (int n[],const int size){
cout<<"Insert elements to fill the array:\n";
for (int i=0;i<size;i++){
cin>>n[i];
}
cout<<"Filling completed.\n";
}
void print (int n[],const int size){
cout<<"The inserted array is:\n";
for (int k=0; k<size; k++)
cout<<n[k]<<" ";
}
仅用于获取数组并打印它。
最佳答案
问题出在你的数组声明上。
int n[]={0};
这告诉编译器你想要一个大小为 1 的数组,其中 n[0] 处的元素初始化为 0。 一旦 i 大于 0,代码就会越界。
int n[大小];
可能是您在这里寻找的。 如果不清楚,请阅读 http://www.cplusplus.com/doc/tutorial/arrays/
关于c++ - 用用户插入的元素填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39435497/