0

这是我的代码:

int main(){

long userInput;
long placeArray[userInput +1];
long divisionPlace, modPlace;
long number = userInput;
long two = 2;

cout << "enter: ";
cin >> userInput;


for (int i = 1; i < userInput; i++) {
    divisionPlace = number / two;
    modPlace = number % two;
    placeArray[number - i ] = modPlace;
}

for (int i = 0; i < userInput; i++) {
    cout << placeArray[i] << " ";
}
cout <<endl;

return 0;
}

有人可以指出我在代码中的错误,为什么我处理错误的内存?

4

2 回答 2

3

正如评论中提到的,您在userInput此处初始化之前正在使用它:

long placeArray[userInput +1];

因此placeArray,当您在下面的循环中访问它时,它不会具有您期望的大小。这将导致写入您未分配的内存,并且会弄乱您的堆栈。

于 2012-10-22T19:17:52.947 回答
1

您的数组分配不正确。

long userInput;

cout << "enter: "; 
cin >> userInput; 

if (userInput <= 0)
{
   cerr << "error" << endl;
   exit(1);
}

long* placeArray = new long[userInput +1]; 

long divisionPlace, modPlace; 
long number = userInput; 
long two = 2; 

for (int i = 1; i < userInput; i++) { 
    divisionPlace = number / two; 
    modPlace = number % two; 
    placeArray[number - i ] = modPlace; 
} 

for (int i = 0; i < userInput; i++) { 
    cout << placeArray[i] << " "; 
} 
cout <<endl; 

delete [] placeArray;
于 2012-10-22T19:18:47.060 回答