NULL
來自 cppreference.com
定義於標頭檔案 <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
|