【发布时间】:2015-02-02 19:18:55
【问题描述】:
我正在尝试编写一些 c++ 代码,它是一个公式的演示,但使用了递归。 这是我的程序及其引发的错误。
环境 - 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() 时抛出异常。
我看到我在做一个非常愚蠢但错综复杂的内存管理错误[并且找不到它]。
任何帮助表示赞赏。
【问题讨论】:
-
C++ 中的数组是零索引的
标签: c++ memory-management stack