c++ - 围绕变量 "random"的堆栈已损坏

标签 c++

我知道之前有人问过这种类型的问题,但我没有看到任何有助于解决此问题的信息。每次编译时,我都会收到 Stack around variable 'random' was corrupted 错误。我不确定是什么原因造成的。我只是想输出 -100 到 100 之间的随机数。

谢谢。

srand((unsigned)time(NULL));

int high = 200;
int low = 100;
const int arraySize = 100;
int random[arraySize];


for (int i = 0; i <= arraySize; i++){
    random[arraySize] = rand() % high - low + 1;
    cout << random[arraySize] << endl;
}

最佳答案

你访问的是random[arraySize],相当于random[100],没有分配。数组大小为 100,因此有效索引为从 099

此外,您可能想在循环内使用 random[i],然后使用

for (int i = 0; i < arraySize; i++){
    random[i] = rand() % high - low + 1;
    cout << random[i] << endl;
}

覆盖所有元素。

关于c++ - 围绕变量 "random"的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33903559/

相关文章:

c++ - 类类似于c++中的NSMutableDictionary

c++ - OpenCV 尝试分配 10 艾字节

c++ - Listen 套接字仅在 g++ 中工作,没有 -std=c++11

c++ - 访问私有(private)类 C++ 内部的结构

c++ - C++ 中的 IPv6 连接测试

c++ - 使用自定义结构作为键类型访问 std::map 会导致奇怪的行为

c++ - 构造函数中的段错误

c++ - 在 QML 场景中显示内存中的网格

c++ - Boost ASIO scatter-gather I/O 导致神秘的内存错误

c++ - 同一段代码,可以在xcode中编译,也可以在terminal中用g++、clang++编译,不能用gcc或clang编译。为什么?