Questions about pointers to pointers and checking if they are NULL
I have an array of pointers. I allocate them to all be 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. 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?
I want to be able to distinguish between a NULL pointer and a pointer that points to something NULL. Here is an iteratio开发者_StackOverflown:
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.
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. So ptr is of type int *
and ptrptr is of type int**
. This means the assignment ptrptr = ptr
is WRONG and your compiler should have noticed that and gave you an warning.
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
}
精彩评论