2012-08-30 67 views
2

什麼是錯的在於:我只是想指針爲int,並給出0指針在C++詮釋

int* p;int* q; 

*p = 0; *q = 0; 
cout<<"p = "<<*p<<" q = "<<*q<<endl; 

是整型值。這是煩人

WORKS:

int* p; 
    *p = 0; 

    cout<<*p<<endl; 

崩潰:

 int* p; 
    int* q; 
    *p = 0; 
    *q = 0; 

    cout<<*p<<endl; 
+0

參見:http://en.wikipedia.org/wiki/Dangling_pointer#Cause_of_wild_pointers –

+0

複製(相同的用戶):如何獲得在C++整數的動態分配的數組的大小](HTTP:// stackoverflow.com/questions/12196712/how-to-get-size-of-a-dynamic-allocated-array-of-ints-in-c) –

+3

@PaulR這是**不**相同的問題! –

回答

5

要使用指針,該指針必須指向某個東西。所以有兩個步驟:創建指針,並創建它指向的東西。

int *p, *q; // create two pointers 
int a;   // create something to point to 
p = &a;  // make p point to a 
*p = 0;  // set a to 0 
q = new int; // make q point to allocated memory 
*q = 0;  // set allocated memory to 0 
+0

您也可以將Luchian Grigore顯示的兩個步驟合併到一行中。 – Derek

+0

@Derek - 當然可以。我正在說明這兩個步驟,將它們結合起來會混淆課程。 –

+1

+1表示您可以創建指向堆棧(a)上的某個指針的指針,而不僅僅是堆(q)。 – Nathan

14
WORKS: 

int* p; 
*p = 0; 

不!它似乎工作,但實際上是未定義的行爲

聲明int* whatever;會給您一個未初始化的指針。你無法解除引用。

要初始化指針&設置它指向0(在你的情況下)的值:

int* p = new int(0); 
+0

那麼如何通過0初始化它?沒有int x = 0; int * p =&x; – Yoda

+0

@RobertKilar見編輯。 –

+0

他應該可能在這裏使用int值而不是int指針... – Inverse

2

你沒有分配任何內存爲您的指針,所以你要未定義行爲。基本上這意味着任何東西都可能發生(包括它也可能工作的可能性)。使用int something = new int(<initialization_value>);來初始化指針。