C通过for循环插入数组

新手上路,请多包涵

我是 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 许可协议

阅读 1.1k
2 个回答
int numArray[] = {0}

在这一行中,您指定 numArray 可以保存一个整数。稍后,当您尝试输入多个整数时,您会得到 未定义的行为。把它想象成一个承诺。这条线是你承诺“给我一个内存位置,我保证我不会在前 n 个 地址之后读取或写入任何内容。”当你违背这个承诺时,理论上任何事情都可能发生。

要修复它,您需要为该数组分配更多内存,并检查以确保您从未定义超过该数字的内容。或者,更简单和更多的 c++ 方法是使用一个数组,它会自动为你做这件事,比如 vector

如果您确实必须使用数组,请确保您有某种方法可以跟踪输入了多少元素。例如:

 const int SIZE = 10;
int numArray[SIZE];

...

std::cout << "Enter the number of values to average (less than " << SIZE << ")" << std::endl;
std::cin >> numVal;
if (numVal >= SIZE)
{
    std::cout << "Please enter a number smaller than " << SIZE << std::endl;
}

原文由 DJMcMayhem 发布,翻译遵循 CC BY-SA 3.0 许可协议

int numArray[] = {0}; 表示创建一个大小为 1 的数组。 C 风格的数组必须在声明中指定它们的大小(显式地,或者从你所做的初始化器的数量中推导出来)。

它们以后不能增长或调整大小。当您执行 cin >> numArray[1] 时,您写入的数组超出范围,导致堆栈损坏。

如果您想要一个可调整大小的数组,那么在 C++ 中称为 vector 。您的代码将是:

 vector<int> numArray;

// ... in loop
int temp = 0;
cin >> temp;
numArray.push_back(temp);

原文由 M.M 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏