2014-12-04 68 views
0

我想寫一些C++代碼,這是一個公式演示,但使用遞歸。 這是我的程序和它拋出的錯誤。在C++ int數組周圍的堆棧損壞錯誤

環境 - 的Visual Studio 2012
編譯 - 成功
運行時異常 -
運行時檢查失敗#2 - 圍繞堆棧變量 'inputNumbers' 已損壞。

碼 -

#include <stdlib.h> 
#include <iostream> 
using namespace std; 


int FindNumber(int Numbers[],int index,int sum, int count) 
{  

    if(count == 0) 
     return sum; 
    else if (count == 1) 
    { 
     sum -= Numbers[index-1]; 
     index = index -1; 
     count = count-1; 
     return sum = FindNumber(Numbers,index,sum,count); 
    } 
    else 
    { 
     sum += Numbers[index-1]; 
     index = index -1; 
     count = count-1; 
     return sum = FindNumber(Numbers,index,sum,count); 
    } 
} 

void main() 
{ 
    int inputNumbers[50]; //declare the series of numbers 
    int cnt = 0; //define and initailize an index counter for inserting the values in number series. 
    int position = 7; //defines the position of the number in the series whose value we want to find. 

    // insert the number series values in the int array. 
    for (int i = 1; i < 51; i++) 
    { 
     inputNumbers[cnt] = i; 
     cnt++; 
     inputNumbers[cnt] = i; 
     cnt++; 
    } 

    cnt=0; 
    for (int i = 1; i < 51; i++) 
    { 
     cout<<inputNumbers[cnt]<<endl; 
     cnt++; 
     cout<<inputNumbers[cnt]<<endl; 
     cnt++; 
    } 

    // set another counter variable to 3 since formula suggests that we need to substrat 3 times from the nth position 
    // Formula : nth = (n-1)th + (n-2)th - (n-3)th 
    cnt = 3; 
    int FoundNumber = 0; 

    //Check if position to be found is greater than 3. 
    if(position>3) 
    { 
     FoundNumber = FindNumber(inputNumbers,position,FoundNumber,cnt); 
     cout<< "The number found is : " << FoundNumber<< endl; 
    } 
    else 
    { 
     cout<<"This program is only applicable for finding numbers of a position value greater than 3..."<<endl;   
    } 

} 

整個程序正在完善按我預期的邏輯,並給出正確的輸出,當我調試,但拋出的異常而退出的main()後執行完成。
我看到我正在做一個非常愚蠢但錯綜複雜的內存管理錯誤[並且找不到它]。
任何幫助表示讚賞。

+0

在C++中的數組是零索引 – Mgetz 2014-12-04 19:24:33

回答

3

難道你不是在這裏填充兩倍大小的數組嗎?

for (int i = 1; i < 51; i++) 
{ 
    inputNumbers[cnt] = i; 
    cnt++; 
    inputNumbers[cnt] = i; 
    cnt++; 
} 
+0

請拿槍,射我的頭......! :/ – user4325846 2014-12-04 19:25:31

1

對於長度爲50的數組,您不能訪問元素49以外的數組;所以代碼應該是這樣的:

int inputNumbers[50]; //declare the series of numbers 
int cnt = 0; //define and initailize an index counter for inserting the values in number series. 

// insert the number series values in the int array. 
for (int i = 0; i < 50; i++) 
{ 
    inputNumbers[cnt] = i; 
    cnt++; 
} 

事實上和上一個答案一樣,您可能只想增加一次cnt。