Latest web development tutorials

C 庫宏– NULL

C 標準庫 - <stddef.h> C標準庫- <stddef.h>

描述

C庫宏NULL是一個空指針常量的值。 它可以被定義為((void*)0), 0或0L ,這取決於編譯器供應商。

聲明

下面是取決於編譯器的NULL 宏的聲明。

#define NULL ((char *)0)

或

#define NULL 0L

或

#define NULL 0

參數

  • NA

返回值

  • NA

實例

下面的實例演示了NULL 宏的用法。

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

int main ()
{
   FILE *fp;

   fp = fopen("file.txt", "r");
   if( fp != NULL ) 
   {
      printf("成功打开文件 file.txt\n");
      fclose(fp);
   }

   fp = fopen("nofile.txt", "r");
   if( fp == NULL ) 
   {
      printf("不能打开文件 nofile.txt\n");
   }
   
   return(0);
}

假設文件file.txt已存在,但是nofile.txt不存在。 讓我們編譯並運行上面的程序,這將產生以下結果:

成功打开文件 file.txt
不能打开文件 nofile.txt

C 標準庫 - <stddef.h> C標準庫- <stddef.h>