gpt4 book ai didi

c - if(!ptr_name) 什么时候为真?

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:25 25 4
gpt4 key购买 nike

下面的代码:

#include<stdio.h>

int is_legal(char* name)
{
if(!name)
return -1;
else
return 0;
}

int main()
{
char* test_name='\0';
printf("is legal return value : %d\n",is_legal(test_name));
return 0;
}

给我结果:

is legal return value : -1

如果将一个字符串分配给 test_name,它会给我一个返回值零,这确实意味着 if(!name) 为 false。

除了将 test_name 分配给 '\0' 之外,是否有任何场景让我得到 if(!name) 为真。

if(!name) 是检查字符串是否为空的标准做法吗?

最佳答案

当指针被转换为 bool 值时,结果是:

  • 如果指针为NULL则为false (0)

  • 否则为真

将 bool 非运算符 (!) 应用于指针会强制转换为 bool 值,然后取反结果值。

此外,指向空字符串""char* 指针不是 NULL 指针。

在您的测试中,您设置了 char* test_name = '\0'; 这意味着 char* test_name = 0; 并且由于 NULL = 0(对于大多数但不是所有的编译器),你有 test_name 是一个 NULL 指针。

另一方面,如果您制作了 char* test_name = "\0";(带双引号),结果将是一个指向空字符串的指针,但是,指针 test_name 本身不是 NULL 指针。

要检查 char* 指针是否有效以及指向的字符串是否为空,您可以这样做:

`if(test_name && *test_name)` // valid pointer and non-empty string

或消极的:

if((test_name == NULL) || (*test_name == '\0')) // invalid pointer or empty string

关于c - if(!ptr_name) 什么时候为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34135307/

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