c - 如何检查指向结构数组的指针在c中是否为空?

标签 c arrays pointers

希望我的问题是可读的..

所以我正在做的是将具有唯一 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/

相关文章:

java - 如何在 Java 中有效地改变字节数组的字节顺序

包含文件的编译错误

C 从控制台读取并写入.txt 文件

java - 如何将图形组件存储在逻辑结构中?

c - 编译自定义 malloc.c 库时出现段错误

c - 将 union 指针声明为函数

c - 神秘双指针赋值的解释

c - 使用 valgrind 修复内存泄漏

c - 使用与引用描述符相同的选项打开新的设备描述符

c++ - 有什么办法可以避免 valarray 和数组之间的复制?