指针和整数之间的比较('int' 和 'void *')- C

comparison between pointer and integer ('int' and 'void *') - C

我正在尝试检查数组的索引是否有值。

void * cols;
...
...

if (((int*)cols)[1]==NULL){
            counter++;
            columns++;

    }
else
{   
    value=((int*)cols)[1];
            fprintf(f, "Validation result from process id: %u. :column %d is invalid\n", (unsigned int)thread_10,value);

}

这给了我警告“指针和整数之间的比较('int' 和 'void *')”。我究竟做错了什么 ?我如何检查索引是否为空?我也无法检查 0,因为 0 在我的例子中是一个有效值,这意味着如果索引包含值 0,则表示它有效。

cols 是一个指针。用 int * 转换后它仍然是一个指针,但现在您将它视为指向 int 的指针。在编写 ((int*)cols)[1] 时,您使用了 void* cols,将其转换为 int*,然后取消引用它,这意味着您现在查看 int,这就是为什么您无法检查 NULL.

(int*)cols 可能是 NULL 或任何其他地址,因此这是您应该检查的变量,((int*)cols)[1] 是地址 int 中的值 cols {some address} + sizeof(int)

所以,if (((int*)cols)[1]==NULL)应该是if (cols)==NULL) {检查[=17时是void*还是int*都没有关系=]}value=((int*)cols)[1]; 就好了