2016-03-07 79 views
0

我在C++初学者的数组,并试图通过for循环将数据插入到一个数组,但是,它抛出Stack around the variable 'numArray' was corrupted.C++插入通过for循环

我的代码:

//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]; 
} 

什么我的代码错了?

编辑:我必须使用数组而不是向量。

+0

是否有任何理由你不使用'std :: vector'或类似的容器? –

+0

你认为在初始化之后数组会有多少元素? – jpw

+0

练习指示我使用数组而不使用矢量,初始化时我们不知道大小 – Shepard

回答

3
int numArray[] = {0} 

在此行中,您可以指定numArray可以容纳一个整数。稍后,当您尝试输入任何多个整数时,您会得到undefined behavior。把这看成是一个承诺。这条线是你有希望的“给我一个内存位置,我保证我不会读或写任何超过第一个地址的地址。”当你违反这个承诺时,任何理论上都可能发生。

为了解决这个问题,你需要为这个数组分配更多的内存,并检查以确保你永远不会定义超过这个数字的东西。或者,更简单,更方便的方法是使用一个可以自动为你做的数组,例如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; 
} 
+0

有雅,有道理,谢谢。这是我的问题的正确答案。 – Shepard

+1

+1,但应该注意的是该数组未初始化。使用'memset'或'int numArray [SIZE] = {0}'初始化为全0,否则数组的内容可能是随机的。 – LINEMAN78

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); 
-1

您正在编写C++,而不是C;使用C++容器类。

std::vector<int> numArray; 
int numVal = 0; 

cin >> numVal; 

numArray.resize(numVal); // add numVal entries to the vector 

for (int i = 0; i < numArray.size(); ++) 
{ 
    cout << "[" << i << "]" = "; 
    cin >> numArray[i]; 
} 
1

假设你想要使用数组动态尽一切:

#include <iostream> 
using namespace std; 

int main() { 
    //Initializing and declairing variables                      
    int numVal = 0; 
    int *numArray; 

    cout << "Enter the number of values to average: "; 
    cin >> numVal; 

    numArray = new int[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]; 
    } 

    delete[] numArray; 

    return 0; 
} 

总是通过调用删除记得自由堆内存。为了达到最佳效果,请始终使用valgrind来测试您的程序。