希望我的问题是可读的..
所以我正在做的是将具有唯一 dataIndex 的项目插入到数组中,但在插入它之前,我需要检查 dataIndex 是否已被使用。
这是我使用的两种结构:
typedef struct item {
float key; // the key for deciding position in heap
unsigned int dataIndex; // a unique id for each item
} HeapItem;
typedef struct heap {
HeapItem *H; // the underlying array
unsigned int *map; //map[i] is the location of item with dataIndex==i
unsigned int n; // the number of items currently in the heap
unsigned int size; // the maximum number of items allowed in the heap
} Heap;
我检查 dataIndex 是这样的:
for (unsigned int i = 0; i < h->n; i++) {
if (h->H[i].dataIndex == dataIndex) {
return HEAP_FAIL;
}
}
但是每次我插入东西时这个 for 循环都会花费 O(n) 次,所以我想做的是:
if (h->map[dataIndex] != NULL ) {
return HEAP_FAIL;
}
但是这段代码不起作用。
所以我的问题是如何检查h->H[h->map[dataIndex]]
是否为空?
下面是我分配 H 和 map 的方式:
h->H = (HeapItem *)malloc(sizeof(HeapItem));
h->map = (unsigned int *)malloc(sizeof(unsigned int));
最佳答案
if (h->map[dataIndex] != NULL ) {
return HEAP_FAIL;
}
它不会工作,因为 h->map[dataIndex]
包含值,而不是地址,上面的 if
将检查值 0
。即使不初始化,任何位置都会有一些垃圾值。
因此,最好的方法是使用某个值进行初始化,例如 -1、无穷大或您认为不会出现在实际值范围内的任何值。
关于c - 如何检查指向结构数组的指针在c中是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29793428/