【问题标题】:Why do I get these warnings?为什么我会收到这些警告?
【发布时间】:2013-05-02 06:35:07
【问题描述】:

编译器对以下代码段显示以下警告。请帮我改正。

if((tmp_n = (struct dot *)shmat(shm_net, NULL, 0)) == (int *) -1) { }
警告:不同指针类型的比较缺少强制转换[默认启用]

它是一个C程序,这个代码段用于将一个共享内存段附加到一个指针**tmp_n,它的类型是struct dot。

struct dot {int weight; int tmv;};

【问题讨论】:

  • 我不确定该警告信息能清晰多少。您正在比较不同的指针类型,而不是先将它们转换为通用类型。

标签: c shared-memory compiler-warnings


【解决方案1】:

试试这个

if((tmp_n = (struct dot *)shmat(shm_net, NULL, 0)) == (void *) -1) { }

看看man-page,上面写着:

Return Value
On success shmat() returns the address of the attached shared memory segment; 
on error (void *) -1 is returned, and errno is set to indicate the cause of the error. 

【讨论】:

  • 但是 (int *) -1 在我的其他程序中工作,没有任何警告。可能是我一开始就写错了,但是因为它好用,而且我用了这么久,发生这种情况时我忘了查手册。
【解决方案2】:

您需要将-1 转换为与您要比较的变量相同的指针类型:

if((tmp_n = (struct dot *)shmat(shm_net, NULL, 0)) == (struct dot *) -1) { }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多