【问题标题】:Assignment makes integer from pointer without a cast [-Werror]赋值从没有强制转换的指针生成整数 [-Werror]
【发布时间】:2012-07-28 02:32:43
【问题描述】:
// set all values in the hash table to null
for(int i = 0; i < HASH_SIZE; i++)
{
    hashtable[i] = NULL;
}

我不断收到此错误消息以响应 hashtable[i]:

赋值从没有强制转换的指针生成整数 [-Werror]

为什么?

【问题讨论】:

    标签: c int


    【解决方案1】:

    如果hashtable 是一个整数数组,那么hashtable[i] 需要一个整数,而NULL 是一个指针。

    因此,您尝试将指针值分配给整数变量(不进行强制转换),这通常只是一个警告,但由于您有 -Werror,所有警告都会变成错误。

    只需使用0 而不是NULL

    【讨论】:

    • 啊,我明白了。我还可以声明一个指针数组并以这种方式存储值。我现在明白了。谢谢!
    【解决方案2】:

    NULL在stddef.h中定义为(void*)0

    #ifndef _LINUX_STDDEF_H
    #define _LINUX_STDDEF_H
    
    #undef NULL
    #if defined(__cplusplus)
    #define NULL 0
    #else
    #define NULL ((void *)0)
    #endif
    
    #endif
    

    如果哈希表是整数数组,比如

    #include <stdio.h>
    #define HASH_SIZE 100
    int main()
    {
    int i = 0, hashtable[HASH_SIZE];
    for(i = 0; i < HASH_SIZE; i++)
    {
        hashtable[i] = NULL;
    }
    return 0;
    }
    

    将显示此warning: assignment makes integer from pointer without a cast

    【讨论】:

    • 是什么让您相信 OP 使用 Linux?是什么让您相信 NULL 必须以这种特殊方式定义?请注意,通过从一个系统推断得出的假设会让您感到意外。相反,阅读和引用 ISO C 标准可能会提供明确的答案。这样的答案与操作系统和标题内容无关。
    • @Jens,谢谢。我将尝试遵循 ISO C std :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2011-07-04
    • 2016-04-22
    相关资源
    最近更新 更多