NULL
来自 cppreference.cn
| 定义于头文件 <locale.h> |
||
| 定义于头文件 <stddef.h> |
||
| 定义于头文件 <stdio.h> |
||
| 在头文件 <stdlib.h> 中定义 |
||
| 定义于头文件 <string.h> |
||
| 定义于头文件 <time.h> |
||
| 在头文件 <wchar.h> 中定义 |
||
| #define NULL /*实现定义*/ |
||
宏 NULL 是一个实现定义的空指针常量,它可以是
|
(自 C23 起) |
空指针常量可以 转换 为任何指针类型;这种转换会产生该类型的空指针值。
目录 |
[编辑] 注意
POSIX 要求 NULL 定义为一个值为 0 并强制转换为 void* 的整数常量表达式。
[编辑] 可能的实现
// C++ compatible: #define NULL 0 // C++ incompatible: #define NULL (10*2 - 20) #define NULL ((void*)0) // since C23 (compatible with C++11 and later) #define NULL nullptr |
[编辑] 示例
运行此代码
#include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> int main(void) { // any kind of pointer can be set to NULL int* p = NULL; struct S *s = NULL; void(*f)(int, double) = NULL; printf("%p %p %p\n", (void*)p, (void*)s, (void*)(long)f); // many pointer-returning functions use null pointers to indicate error char *ptr = malloc(0xFULL); if (ptr == NULL) printf("Out of memory"); else printf("ptr = %#" PRIxPTR"\n", (uintptr_t)ptr); free(ptr); }
可能的输出
(nil) (nil) (nil) ptr = 0xc001cafe
[编辑] 参见
| (C23) |
预定义空指针常量 nullptr 的类型 (typedef) |
| C++ 文档 关于 NULL
| |