分段故障(堆芯)递归函数

Segmentation fault (core dumped) recursive function

本文关键字:递归函数 堆芯 故障 分段      更新时间:2023-10-16

我得到这个递归函数的分割错误(核心转储),以计数由用户输入的字符串中的元音。我的目标是将用户输入的字符串变量复制到字符数组中,然后小写并验证该字符是否为元音。验证后,该函数应执行元音计数的递归加法。在这个函数中,我传递了一个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;
}

你的代码有几个问题:

  1. 你通过值传递字符串,这是昂贵的,你经常这样做。
  2. 你复制你的字符串到一个数组?不必要的。如果您想通过索引访问,只需在字符串上使用[]操作符。为什么不使用迭代器代替基于索引的访问和传递字符串?
  3. 为什么递归?对于这项工作,迭代将是伟大的。
  4. 正如三十二上校所提到的,托洛尔没有修改论点。

为什么会出现分段故障?

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;
}