在c++中停止使用nullptr
Stop a while with nullptr in c++
我尝试在一段时间内使用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;
}
相关文章:
- 如何在自删除后将对象设置为nullptr
- 如何取消对nullptr的屏蔽,返回正确的对象
- C++ - "!pointer"和"pointer == nullptr"的区别?
- 将指针设置为"nullptr"并不能防止双重删除?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 为什么我的节点在我设置后被设置为 nullptr = 新节点?
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- wx通用目录控制错误"wxTheFileIconsTable was nullptr"
- 当设置为 const 变量时使用 nullptr
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 检查类方法中是否(此 == nullptr)
- C++98,但叮叮当当地说使用nullptr?
- 为什么调试器引发"read access violation. this was nullptr"异常?
- 检查模板中 nullptr 的函数指针,了解任何类型的可调用对象
- 检查nullptr是否100%保护内存布局不受segfault影响
- 向unordered_map添加unique_ptr时'this was nullptr'
- 使用 nullptr 作为 std::unordered_map 的键有什么后果吗?