我是 C++ 的初学者,并试图通过 for 循环将数据插入到数组中,但是,它抛出 Stack around the variable 'numArray' was corrupted.
我的代码:
//Initializing and declairing variables
int numVal = 0;
int numArray[] = {0};
cout << "Enter the number of values to average: ";
cin >> numVal;
//Loop through to accept all values and allocate them to an array
for (int i = 0; i < numVal; i++) {
cout << "[" << i << "] = ";
cin >> numArray[i];
}
我的代码有什么问题?
编辑:我必须使用数组而不是向量。
原文由 Shepard 发布,翻译遵循 CC BY-SA 4.0 许可协议
在这一行中,您指定 numArray 可以保存一个整数。稍后,当您尝试输入多个整数时,您会得到 未定义的行为。把它想象成一个承诺。这条线是你承诺“给我一个内存位置,我保证我不会在前 n 个 地址之后读取或写入任何内容。”当你违背这个承诺时,理论上任何事情都可能发生。
要修复它,您需要为该数组分配更多内存,并检查以确保您从未定义超过该数字的内容。或者,更简单和更多的 c++ 方法是使用一个数组,它会自动为你做这件事,比如 vector 。
如果您确实必须使用数组,请确保您有某种方法可以跟踪输入了多少元素。例如: