c - 当我们将 "if(ptr==NULL)"用作整数指针 ptr 时,NULL 指针是否隐式转换为类型 (int*)?

标签 c casting void-pointers null-pointer

我知道 NULL 指针是 (void*)0。但是当我们使用如下语句时会发生什么:

  if(ptr==NULL)

ptr可以是charfloatint指针?是NULL 保证被隐式转换为左边的类型,例如,在 C 中,malloc() 返回的类型是 void* 但被隐式转换到左值的类型?

最佳答案

Is NULL guaranteed to be implicitly converted to the type on the left? [...]

是的。

根据 ISO/IEC 9899:2011 C programming language standard 的第 6.3.2.3.4 节:

Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

和第 6.3.2.3.1 节

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

关于c - 当我们将 "if(ptr==NULL)"用作整数指针 ptr 时,NULL 指针是否隐式转换为类型 (int*)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16563342/

相关文章:

c - 尝试通过冒泡排序对名称链接列表进行排序时出现段错误

c# - 使用 "ref"和/或 "out"作为对象类型

c++ - void * 转换为 int 语法的问题

c - 解决 time.h 中 timespec 的重新定义

c - 合并 C Dll 的最简单方法。有来源

c - 无符号长 0 < -1?

casting - Java 7 : Cannot cast from Object to int etc

c# - 为什么不能将 Double 隐式转换为 Decimal

c - 在 C 中复制 char* 的通用函数