【问题标题】:C++ segmentation fault while counting character occurrences in string计算字符串中出现的字符时出现 C++ 分段错误
【发布时间】:2017-09-30 18:27:09
【问题描述】:

我编写了一个简单的函数来计算字符串中某个字符的出现次数。编译器没问题。但是,当我尝试运行它时,它产生了分段错误。

#include <iostream>
using namespace std;

// To count the number of occurences of x in p
// p is a С-style null-terminated string
int count_x(char* p, char x)
{
    if (p == nullptr)
    {
        return 0;
    }

    // start the counter
    int count = 0;
    while (p != nullptr)
    {
        if (*p == x)
        {
            ++count;
        }
    }

    return count;
}

int main(int argc, char const *argv[])
{
    char myString[] = "Hello";
    cout << count_x(myString, 'l');
    return 0;
}

【问题讨论】:

  • 你相信p会通过什么魔法变成nullptr?循环条件永远不会变为假 - 相反,p 会在字符串末尾运行并开始访问随机内存地址,因此您的程序会表现出未定义的行为。
  • 是的。将 nullptr 更改为 NULL... 这可以工作。
  • 我看不出p 有什么变化。对我来说,这就像一个无限循环。
  • @RetiredNinja 是的......我错过了那条线。 p++。谢谢你。你最近好吗?
  • 您的代码已损坏。只需使用 Viktor Alkhimov 提供的答案。在处理 C++ 中的文本时,总是 转到 std::string。

标签: c++ pointers segmentation-fault c-strings


【解决方案1】:

你的代码有两个错误:

  1. 您只能查看字符串中的第一个字符。
  2. 以空字符结尾的字符串的最后一个字符是空字符。您正在测试指针本身。

【讨论】:

  • 感谢@Bill Lynch,我把我的代码改成了这个,它可以工作了。 int count_x(char* p, char x) { if (*p=='\0') { return 0; } //启动计数器 int count=0; while(*p!='\0') { if (*p==x) { ++count; } p++; } 返回计数; }
  • 不确定我是疯了还是其他支持者疯了。这与 OP 的代码几乎是相同的问题。您仅在匹配时增加计数。如果第一个字符不匹配,它仍然会永远循环。
  • @texasbruce:是的。这很伤心。谢谢。
【解决方案2】:

你需要使用 std::string

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
     std::string str = "Hello";
     std::cout << std::count(str.begin(), str.end(), 'l');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2017-08-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多