【发布时间】: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