C++ 中的懸空指標、空指標、空指標和野指標


懸空指標

懸空指標是指向已被釋放(或刪除)的記憶體位置的指標。指標充當懸空指標的方式有很多種。

函式呼叫

當局部變數不是靜態時,指向區域性變數的指標在區域性變數超出作用域時會變成懸空指標。

int *show(void) {
   int n = 76; /* ... */ return &n;
}

輸出

Output of this program will be garbage address.

記憶體的釋放

int main() {
   float *p = (float *)malloc(sizeof(float));
   //dynamic memory allocation.
   free(p);
   //after calling free()
   p becomes a dangling pointer p = NULL;
   //now p no more a dangling pointer.
}

變數超出作用域

int main() {
   int *p //some code// {
      int c; p=&c;
   }
   //some code//
   //p is dangling pointer here.
}

空指標

空指標是指與任何資料型別都不關聯的指標。它指向儲存器中的某個資料位置,即指向變數的地址。它也被稱為通用指標。

它有一些限制

  • 由於空指標的具體大小,因此無法對其進行指標運算。
  • 它不能用作解引用。

示例

#include<stdlib.h>
#include<iostream>
using namespace std;
int main() {
   int a = 7;
   float b = 7.6;
   void *p;
   p = &a;
   cout<<*( (int*) p)<<endl ;
   p = &b;
   cout<< *( (float*) p) ;
   return 0;
}

輸出

7
7.600000

演算法

Begin
   Initialize a variable a with integer value and variable b with float value.
   Declare a void pointer p.
   (int*)p = type casting of void.
   p = &b mean void pointer p is now float.
   (float*)p = type casting of void.
   Print the value.
End.

空指標

空指標是指向任何東西的指標。

空指標的一些用途是

  • 當指標變數尚未分配任何有效記憶體地址時,初始化指標變數。

  • 如果我們不想傳遞任何有效記憶體地址,則將空指標傳遞給函式引數。

  • 在訪問任何指標變數之前檢查空指標。這樣,我們可以在與指標相關的程式碼中執行錯誤處理,例如,僅當指標不為 NULL 時才解引用指標變數。

示例

即時演示

#include <iostream>
using namespace std;
int main() {
   int *p= NULL; //initialize the pointer as null.
   cout<<"The value of pointer is ";
   cout<<p;
   return 0;
}

輸出

The value of pointer is 0.

野指標

野指標是指向某個任意記憶體位置的指標。(甚至不是 NULL)

int main() {
   int *ptr; //wild pointer
   *ptr = 5;
}

更新於: 2019-07-30

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.