2011-04-24 26 views
1

我有一個指針數組。我將它們全部分配給NULL。我改變了一些指針,以便其中的一些指向一個爲NULL的元素,其中一些指向一個元素。我遍歷數組中的所有指針。我的問題是,如何檢查實際指針是否爲NULL,而不是它們指向的元素是否爲NULL?有關指向指針的指針並檢查它們是否爲空的問題

我希望能夠區分NULL指針和指向NULL的指針。下面是一個迭代:

if (ptrptr == NULL) { 
    // The actual pointer is NULL, so set it to point to a ptr 
    ptrptr = ptr; 
} else { 
    // The pointer points to SOMETHING, it may be NULL, it may not be, but the ptrptr itself is not NULL 
    // Do something 
} 

會發生什麼事,是我所ptrptr指向PTR,由於PTR爲NULL,我越來越爲NULL ptrptr,即使它指向的東西。

回答

1

您需要分配內存來保存指針並將其解除引用。

if (ptrptr == NULL) { 
    // The actual pointer is NULL, so set it to point to a ptr 
    ptrptr = malloc(sizeof(ptr)); 
    *ptrptr = ptr; 
} else { 
    // The pointer points to SOMETHING, it may be NULL, it may not be, but the ptrptr itself is not NULL 
    // Do something 
} 
+0

是否ptrptr = malloc的(的sizeof(PTR))改變到ptrptr PTR或者它改變其將指向的地方的尺寸的大小? – gegardmoussasi 2011-04-24 22:17:34

+0

它使'ptrptr'指向可以容納'ptr'的地方。當你完成時,不要忘記釋放。 – 2011-04-24 22:18:43

0

舉例來說,讓我們假設你的對象到底是int s。因此,ptr的類型爲int *,ptrptr的類型爲int**。這意味着分配ptrptr = ptr是錯誤的,您的編譯器應該已經注意到並給了您警告。

例如:

#define N 100 

int* my_arr[N]; //My array of pointers; 
//initialize this array somewhere... 

int **ptrptr; 
for(ptrptr = my_arr; ptrptr < my_arr + N; ptrptr++){ 
    ptr = get_object(); 
    *ptrptr = ptr; //This is equivalent to my_array[i] = ptr 
}