关于演员的编译器警告

时间:2017-10-09 13:16:11

标签: c linux gnu

我正在测试示例代码如下,为什么我在linux ubuntu 16-4上通过gcc 5.6编译时会收到警告?

~/c$ gcc malloc.c 
malloc.c: In function ‘main’:
malloc.c:17:14: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
     if(number= malloc(50*sizeof(int) )== NULL)

这是我的代码:

#include "stdlib.h"
#include "stdio.h"

int main()
{
    char* str;
    int * number;
    if((str= (char *)malloc(100) )== NULL)
    {
        printf("malloc fail \n");
        exit(1);
    }

    printf ("sting was allocaed \n");
    if(number= malloc(50*sizeof(int) )== NULL)
    {
        printf("malloc fail \n");
        exit(1);
    }

    printf ("int was allocaed \n");
    return 0;
}

1 个答案:

答案 0 :(得分:3)

这里

number= malloc(50*sizeof(int) )== NULL 

您从numbermalloc的回复中分配NULL比较结果,因为==的优先级高于=

幸运的是,编译器捕获了因为number是一个指针。

你需要这样做:

(number = malloc(50*sizeof(int)) )== NULL

注意:如果您有疑问,请插入一些括号。它不花一分钱。

另外,你很幸运,编译器使用默认警告级别捕获了它。将来,请始终编译并启用所有警告-Wall并添加-Wextra -pedantic

请注意,您的第一次分配(几乎)没问题:

if((str= (char *)malloc(100) )== NULL)

除了[你不应该在C中投射malloc的输出[1]所以:

if((str= malloc(100) )== NULL)

甚至更好(是的,无需乘以sizeof(char),总是1)

相关问题