C/C++ 中為什麼把零地址用於空指標?


空指標是指向“無”的指標。

空指標有一些用途

b) 當沒有為指標變數分配任何有效記憶體地址時,初始化指標變數。

b) 當我們不想傳遞任何有效記憶體地址時,將空指標傳遞給函式引數。

c) 在訪問任何指標變數之前,檢查空指標。以便我們可以在與指標相關的程式碼中執行錯誤處理,例如僅在指標變數不為空時取消引用該指標變數。

在 C++ 中,如果我們在任何指標中分配 0,這意味著該指標指向空(NULL)。

語法

Float *p = 0 //initializing the pointer as NULL.

演算法

Begin.
   Declare a pointer p of the integer datatype.
      Initialize *p= NULL.
   Print “The value of pointer is”.
      Print the value of the pointer p.
End.

示例

 線上演示

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

輸出

The value of pointer is 0.

更新日期:2019 年 7 月 30 日

530 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.