简体   繁体   English

有关指向指针并检查它们是否为NULL的问题

[英]Questions about pointers to pointers and checking if they are NULL

I have an array of pointers. 我有一个指针数组。 I allocate them to all be NULL. 我将它们全部分配为NULL。 I change some of the pointers so that some of them point to an element that is NULL and some of them point to an element. 我更改了一些指针,以使其中一些指向NULL元素,而另一些指向元素。 I am iterating through all of the pointers in the array. 我正在遍历数组中的所有指针。 My question is, how do I check that the actual pointers are NULL and not the elements that they are pointing to are NULL? 我的问题是,如何检查实际指针是否为NULL,而不是它们指向的元素是否为NULL?

I want to be able to distinguish between a NULL pointer and a pointer that points to something NULL. 我希望能够区分NULL指针和指向NULL的指针。 Here is an iteration: 这是一个迭代:

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
}

What happens is that I set ptrptr to point to ptr, and since ptr is NULL, I am getting NULL for ptrptr even though it points to something. 发生的事情是我将ptrptr设置为指向ptr,并且由于ptr为NULL,所以即使ptrptr指向某物,我也得到NULL。

You need to allocate memory to hold the pointer, and dereference into it. 您需要分配内存来保存指针,然后对其取消引用。

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
}

For example's sake, lets suppose your objects in the end are int s. 例如,让我们假设您的对象最后是int So ptr is of type int * and ptrptr is of type int** . 所以ptr是int *类型,而ptrptr是int**类型。 This means the assignment ptrptr = ptr is WRONG and your compiler should have noticed that and gave you an warning. 这意味着分配ptrptr = ptr是错误的,您的编译器应该已经注意到这一点,并给了您警告。

For example: 例如:

#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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM