我有一个指针数组。我将它们都分配为空。我更改了一些指针,使其中一些指针指向一个空元素,而另一些指针指向一个元素。我遍历了数组中的所有指针。我的问题是,如何检查实际指针是否为空,而不是它们所指向的元素是否为空?
我希望能够区分空指针和指向空对象的指针。下面是一个迭代:
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,所以即使ptrptr指向某些东西,我也会得到NULL。
发布于 2011-04-25 05:47:34
你需要分配内存来保存指针,并取消对它的引用。
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
}发布于 2011-04-25 06:02:05
例如,假设你的对象最后是ints,那么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
}https://stackoverflow.com/questions/5773426
复制相似问题