分段故障(堆芯)递归函数
Segmentation fault (core dumped) recursive function
我得到这个递归函数的分割错误(核心转储),以计数由用户输入的字符串中的元音。我的目标是将用户输入的字符串变量复制到字符数组中,然后小写并验证该字符是否为元音。验证后,该函数应执行元音计数的递归加法。在这个函数中,我传递了一个0的整数作为参数int L。关于我能做些什么来修复和改进这部分代码的任何信息将是很棒的。
#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
using namespace std;
int vowels(string s, int L)
{
int sum = 0;
char str[s.length()-1];
strcpy(str,s.c_str());
if(str[L])
{
tolower(str[L]);
if(str[L]!='a'||str[L]!='e'||str[L]!='i'||str[L]!='o'||str[L]!='u')
sum = 0;
else
sum = 1;
return sum += vowels(s,L++);
}
else
return 0;
}
你的代码有几个问题:
- 你通过值传递字符串,这是昂贵的,你经常这样做。 你复制你的字符串到一个数组?不必要的。如果您想通过索引访问,只需在字符串上使用
- 为什么递归?对于这项工作,迭代将是伟大的。
- 正如三十二上校所提到的,托洛尔没有修改论点。
[]
操作符。为什么不使用迭代器代替基于索引的访问和传递字符串?为什么会出现分段故障?
strcpy
复制字符串直到到达空字符。所以你需要一个s.length()+1
元素的字符数组,而不是s.length()-1
,如果没有分割错误发生。
int vowels(string::const_iterator beg, string::const_iterator end) {
int sum = 0;
if (beg != end) {
switch (*beg) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return 1 + vowels(++beg, end);
}
return vowels(++beg, end);
}
return 0;
}
工作代码:#include <string>
#include <iostream>
using namespace std;
int vowels(string::const_iterator beg, string::const_iterator end) {
int sum = 0;
if (beg != end) {
switch (*beg) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return 1 + vowels(++beg, end);
}
return vowels(++beg, end);
}
return 0;
}
int main() {
string x = "hello canberk";
cout << vowels(x.begin(), x.end()) << endl;
return 0;
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 递归函数有效,但无法记忆
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么递归函数的最终输出是 5?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 如何将记忆应用于此递归函数?
- 如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
- 无穷大而循环时具有递归函数
- 即使没有调用这个递归函数,它是如何工作的?
- 如何使此递归函数从给定的起始位置返回最小的整数?
- 此递归函数的每次迭代的值存储在哪里?
- 可以清除递归函数中的变量吗?
- 如何在递归函数调用中返回当前函数值
- 递归函数 c++ 的复杂性
- 这个递归函数有什么作用?运行时的复杂性是多少?
- 任何人都可以查明我的递归函数中的错误吗?
- 在递归函数中释放内存时堆损坏
- 在递归函数中,堆上分配vs堆栈上分配
- 分段故障(堆芯)递归函数