NULL
来自cppreference.com
| 在标头 <locale.h> 定义
|
||
| 在标头 <stddef.h> 定义
|
||
| 在标头 <stdio.h> 定义
|
||
| 在标头 <stdlib.h> 定义
|
||
| 在标头 <string.h> 定义
|
||
| 在标头 <time.h> 定义
|
||
| 在标头 <wchar.h> 定义
|
||
| |
||
宏 NULL 是实现定义的空指针常量,可为
|
(C23 起) |
空指针常量能转换为任何指针类型;转换结果是该类型的空指针值。
注解
POSIX 要求 NULL 被定义为转换为 void* 的值为 0 的整数常量表达式。
可能的实现
|
示例
运行此代码
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// 任何类型的指针均能设为 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);
// 多数返回指针的函数用空指针指示错误
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) |
NULL 的 C++ 文档
| |