Cprogramming 简明教程

NULL Pointer in C

NULL Pointer in C

C 中的 NULL pointer 是一个不指向任何内存位置的指针。NULL 常量在头文件 stdio.hstddef.h 以及 stdlib.h 中定义。

A NULL pointer in C is a pointer that doesn’t point to any of the memory locations. The NULL constant is defined in the header files stdio.h, stddef.h as well as stdlib.h.

指针初始化为 NULL 以避免程序的不可预知行为或防止段错误。

A pointer is initialized to NULL to avoid the unpredicted behavior of a program or to prevent segmentation fault errors.

Declare and Initialize a NULL Pointer

以下是你申明并初始化一个 NULL 指针的方式 −

This is how you would declare and initialize a NULL pointer −

type *ptr = NULL;

或者,你也可以使用此语法 −

Or, you can use this syntax too −

type *ptr = 0;

Example of a NULL Pointer

以下示例演示了如何申明并初始化一个 NULL 指针 −

The following example demonstrates how to declare and initialize a NULL pointer −

#include <stdio.h>

int main() {
   int *p= NULL;//initialize the pointer as null.
   printf("The value of pointer is %u",p);
   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

The value of pointer is 0.

Applications of NULL Pointer

以下是 NULL 指针的一些应用:

Following are some of the applications of a NULL pointer −

  1. To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.

  2. To pass a null pointer to a function argument when we don’t want to pass any valid memory address.

  3. To check for a null pointer before accessing any pointer variable so that we can perform error handling in pointer-related code. For example, dereference a pointer variable only if it’s not NULL.

NULL 指针始终用于检测 treeslinked lists 和其他动态数据结构的端点。

A NULL pointer is always used to detect the endpoint of trees, linked lists, and other dynamic data structures.

Check Whether a Pointer is NULL

通常会建议在解除引用指针来获取其目标变量的值之前,检查该指针是否为 NULL。

It is always recommended to check whether a pointer is NULL before dereferencing it to fetch the value of its target variable.

Example

请看以下示例:

Take a look at the following example −

#include <stdio.h>

int main(){

   int *ptr = NULL;   // null pointer

   if (ptr == NULL) {
      printf("Pointer is a NULL pointer");
   }
   else {
      printf("Value stored in the address referred by the pointer: %d", *ptr);
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Pointer is a NULL pointer

Check Memory Allocation Using NULL Pointer

函数 malloc()calloc() 用于动态分配内存块。如果成功,此类函数会返回指向已分配块的指针;如果失败,则返回 NULL。

The malloc() and calloc() functions are used to dynamically allocate a block of memory. On success, these functions return the pointer to the allocated block; whereas on failure, they return NULL.

Example

以下示例展示了如何使用 NULL 指针来检查内存分配是否成功 −

The following example shows how you can use the NULL pointer to check whether memory allocation was successful or not −

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

int main(){

   int* ptr = (int*)malloc(sizeof(int));


   if (ptr == NULL){
      printf("Memory Allocation Failed");
      exit(0);
   }
   else{
      printf("Memory Allocated successfully");
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

Memory Allocated successfully

NULL File Pointer

通常应使用建议方式来检查 fopen() function 返回的 FILE pointer 是否为 NULL,以避免文件相关处理的运行时错误。

Checking if the FILE pointer returned by the fopen() function is NULL is always a recommended approach to avoid runtime errors in file-related processing.

Example

以下示例展示了如何使用 NULL 文件指针来确保文件是否可访问 −

The following example shows how you can use the NULL file pointer to ensure that a file is accessible or not −

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

int main(){

   FILE *fp;
   char *s;
   int i, a;
   float p;

   fp = fopen ("file3.txt", "r");

   if (fp == NULL){
      puts ("Cannot open file"); return 0;
   }

   while (fscanf(fp, "%d %f %s", &a, &p, s) != EOF)
      printf ("Name: %s Age: %d Percent: %f\n", s, a, p);

   fclose(fp);

   return 0;
}

当还没有为目标变量分配任何有效内存地址的时候,你应该始终将指针变量初始化为 NULL。

You should always initialize a pointer variable to NULL when the target variable hasn’t been assigned any valid memory address yet.