C C 的空指標,NULL,0和nullptr

2021-09-17 18:59:26 字數 1442 閱讀 8309

在c和c++中,null和0都可以使用。

c通常使用null,c++通常使用0

#include int main(void)
#include using namespace std;

int main() // #1

void foo(char*) {} // #2

int main()

void foo(int)   {}   // #1

void foo(char*) {} // #2

int main()

在c/c++中,null的位址均不可訪問,也就是不能取出null代表的位址上的值

int *p=null;

int a=*p;

//error

解析:main()裡的node呼叫fun()函式,傳入引數node,fun()裡的node其實是傳遞指標,int *node=node,前者node是fun()作用域裡的指標,後者是main()作用域裡的指標。fun()裡改變fun()作用域的node的指向,可以輸出100。但回到main()時,因為它改變的是指標的指向,而不是指標的值(指標的傳遞知識:所以改變不可以被傳遞,即fun()裡的fun()作用域的node由於是區域性變數被釋放,main()裡的main()作用域的node其實沒有任何改變,還是指向null,訪問出錯。

#include void fun(int *node)

int main()

改變傳遞的指標的值解決錯誤: 

解析:改變傳遞的指標的指向不可以傳遞改變,而改變傳遞的指標的值則可以傳遞改變。

#include void fun(int *&node)

int main()

使用二級指標解決錯誤:

解析:int **node是乙個二級指標,fun(&node)傳遞的是node的位址。fun()裡**node是&node,即node本身變數名儲存的位址,*node是node的指向的位址,讓node指向了100,因為*node是改變指標的值,所以改變可以被傳遞。

#include void fun(int **node)

int main()

使用引用操作符:

解析:引用改變的被傳遞的引數

#include void fun(int *&node)

int main()

參考:

c c 中空指標,空指標常量,NULL

如何是乙個指標變數成為空指標 如果 p 是乙個指標變數,則 p 0 p 0l p 0 p 3 3 p 0 17 中的任何一種賦值操作之後 對於 c 來說還可以是 p void 0 p 都成為乙個空指標,由系統保證空指標不指向任何實際的物件或者函式。null 是乙個標準規定的巨集定義,用來表示空指標常...

C 空指標 NULL 與0的區別

空指標常量,ansi規定 規定預處理巨集null 為空指標常量,通常 define null 0或 void 0 誤區 有的機器不同型別的指標使用不同的內部表示,例如將字元指標的空指標常量定義為 define null char 0 這樣的null定義對於接受字元指標的函式沒有問題,但對於其他型別的...

空指標 從 0 到 NULL,再到 nullptr

nullptr null 是乙個巨集定義 undef null if defined cplusplus define null 0 else define null void 0 endifint my ptr 0 int my ptr null null 的問題 include void f c...