[英]Why am i getting a stack overflow? Advice would be greatly appreciated
So, I'm very new to coding and i do apologize beforehand if my code makes you cringe.所以,我对编码很陌生,如果我的代码让你畏缩,我会事先道歉。 I have a coding homework to write a program that displays the c_string in all uppercase characters using a recursive function.
我有一个编码作业来编写一个程序,该程序使用递归 function 以所有大写字符显示 c_string。 When running my code, i get an out put of "A" then i get a stack overflow and i don't know why.
运行我的代码时,我得到一个输出“A”,然后我得到一个堆栈溢出,我不知道为什么。 Please assist me to help me understand where i went wrong with my code.
请帮助我了解我的代码哪里出错了。 Also, if you have any advice on how i should have coded differently for this problem, please let me know!
另外,如果您对我应该如何针对这个问题进行不同的编码有任何建议,请告诉我!
I tried changing using a for loop but I'm reading online that its an iteration function and doesn't work with recursive.我尝试使用 for 循环进行更改,但我在网上阅读它的迭代 function 并且不适用于递归。
#include <iostream>
#include <ctype.h>
using namespace std;
void showInUpper(char alphabet[], int i);
int main()
{
char alphabet[27]{ "abcdefghijklmnopqrstuvwxyz" };
int i = 0;
showInUpper(alphabet, i);
cout << endl << endl;
}
void showInUpper(char alphabet[], int i)
{
if (alphabet[i] == '\0')
{
return;
}
else if (alphabet[i] != toupper(alphabet[i]))
{
alphabet[i] = toupper(alphabet[i]);
cout << alphabet[i] << '\t';
}
showInUpper(alphabet, i++);
}
So, the expected results should look like this.所以,预期的结果应该是这样的。
ABCDEFGHIJKLMNOPQRSTUVWZXYZ ABCDEFGHIJKLMNOPQRSTUVWZXYZ
You're passing the same value of i
to each invocation of showInUpper
because i
doesn't get incremented until after it is passed to the function.您将相同的
i
值传递给showInUpper
的每次调用,因为i
在传递给 function 之前不会递增。 As a result you have endless recursion.结果,您有无休止的递归。
Use the pre-increment operator instead:请改用预增量运算符:
showInUpper(alphabet, ++i);
so that i
is incremented before it is passed.以便
i
在通过之前递增。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.