C 庫 - NULL 宏



C 庫中的 NULL 宏表示空指標常量的值,它可以定義為((void*)0), 00L,具體取決於編譯器廠商。

以下是 NULL 宏結構的列表:

  • NULL (void*)0:一個空指標強制轉換為 void* 型別。
  • NULL 0:一個表示空指標的整型字面量。
  • NULL 0L:一個表示空指標的長整型字面量。

語法

以下是 C 庫中 NULL 宏的語法。

#define NULL ((char *)0)

or,

#define NULL 0L

or

#define NULL 0

引數

  • 這不是一個函式。因此,它不接受任何引數。

返回值

  • 此宏不返回任何值。

示例 1

以下是用 C 庫宏 NULL 宏演示檔案處理的基本示例。

#include <stddef.h>
#include <stdio.h>

int main () {
   FILE *fp;

   fp = fopen("file.txt", "r");
   if( fp != NULL ) {
      printf("Opend file file.txt successfully\n");
      fclose(fp);
   }

   fp = fopen("nofile.txt", "r");
   if( fp == NULL ) {
      printf("Could not open file nofile.txt\n");
   }
   
   return(0);
}

輸出

假設我們有一個已存在的file.txt檔案,但nofile.txt檔案不存在。編譯上述程式後,我們將得到以下結果:

Opend file file.txt successfully
Could not open file nofile.txt

示例 2

下面的程式演示了使用 errno(宏)處理記憶體分配錯誤。

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main() {
   size_t size = 100000000000;

   int *arr = malloc(size * sizeof(int));
   if (arr == NULL) {
       fprintf(stderr, "Memory allocation failed: %s\n", strerror(errno));
   } else {
       printf("Memory allocated successfully!\n");
       free(arr);
   }

   return 0;
}

輸出

執行上述程式碼後,我們將得到以下結果:

Memory allocation failed: Cannot allocate memory
廣告
© . All rights reserved.