在c++中停止使用nullptr

Stop a while with nullptr in c++

本文关键字:nullptr c++      更新时间:2023-10-16

我尝试在一段时间内使用nullptr,如果是空指针停止while。

#include <iostream>
using namespace std;
int count_x(char* p, char x)
{
  int count = 0;
  while(p)
  {
    if (*p==x)
      ++count;
    ++p;
  }
  return count;
}
int main(int argc, char *argv[])
{
  char *arr = "aabbaa";
  char s = 'a';
  cout << count_x(arr, s) << endl;
  return 0;
}

但是这段代码,当我执行时,我得到这个消息

Bus error: 10

我用这行

编译
g++ -std=c++11 -o count_x count_x.cpp

字符串以零结尾,这意味着它的最后一个字节是0。如果增加指针,需要检查指针是否指向 0,而不是 0。

#include <iostream>
using namespace std;
int count_x(char* p, char x)
{
    int count = 0;
    while (*p)
    {
        if (*p == x)
            ++count;
        ++p;
    }
    return count;
}
int main(int argc, char *argv[])
{
    char *arr = "aabbaa";
    char s = 'a';
    cout << count_x(arr, s) << endl;
    return 0;
}

使用while(p),您将运行很长时间(或者更有可能,执行内存访问冲突并比这更快地生成分段错误)。

把这个放在一边,正式的描述是,一旦p指向它最初指向的字符串的内存边界之外,*p == x将产生未定义的行为。

长话短说,把while (p)改成while (*p),或者直接做:

for (int i=0; p[i]; i++)
{
    if (p[i] == x)
        ++count;
}