gpt4 book ai didi

c++ - 为什么指向 NULL 字符的指针未转换为 false

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:08:10 25 4
gpt4 key购买 nike

我认为指向NULL 的指针可以转换为0。所以我写了下面的程序:

#include <iostream>
#include <regex>
#include <string>
#include <cstdlib>

bool is_strtoi(const std::string& str)
{
char *p;
std::strtol(str.c_str(), &p, 10);
return *p == '\0';
}

bool is_strtoi1(const std::string& str)
{
char *p;
std::strtol(str.c_str(), &p, 10);
return p; //Pointer to NULL should be converted to false;
}

int main ()
{
std::string test1("123asd2");
std::string test2("123123");
std::cout << is_strtoi1(test1) << std::endl;
std::cout << is_strtoi1(test2) << std::endl;
std::cout << "---" << std::endl;
std::cout << is_strtoi(test1) << std::endl; //prints 1
std::cout << is_strtoi(test2) << std::endl;
}

根据标准的 4.12 部分:

A zero value, null pointer value, or null member pointer value is converted to false

那为什么没有呢?

最佳答案

你是一层间接出来的! “空指针”和“指向空/零的指针”是两个不同的东西。

最基本的:

  • 空指针本身的值为零。
  • 它不指向其他值为零的对象。

p  == 0;  // yes
*p == 0; // no

确实,指向长度为 0 的 C 字符串的 char*(即 {'\0'})不是空指针;这是一个完全有效的指针。

不过,更进一步,指针可以“具有零值”的概念实际上是一个实现细节。抽象地说,指针不是数字,因此我们不应将空指针视为具有数值(例如零)。这在引入不能隐式转换为整数的 nullptr 关键字时很明显。通过删除关于“零”的整个讨论,我们可以改为给出以下改进的、更合适的示例:

p  == nullptr; // yes
*p == '\0'; // no

关于c++ - 为什么指向 NULL 字符的指针未转换为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30944780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com