NULL
来自 cppreference.cn
定义于头文件 <locale.h> |
||
定义于头文件 <stddef.h> |
||
定义于头文件 <stdio.h> |
||
定义于头文件 <stdlib.h> |
||
定义于头文件 <string.h> |
||
定义于头文件 <time.h> |
||
定义于头文件 <wchar.h> |
||
#define NULL /*implementation-defined*/ |
||
宏 NULL
是一个实现定义的空指针常量,它可以是
- 一个值为 0 的整数常量表达式
- 一个值为 0 的整数常量表达式 强制转换为类型 void*
|
(自 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
|