我正在测试如下示例代码,为什么在 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;
}
最佳答案
这里
number= malloc(50*sizeof(int) )== NULL
您将 malloc
和 NULL
返回的比较结果分配给 number
,因为 ==
的优先级高于 =
。
幸运的是,编译器捕获了这一点,因为 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)
关于c - 关于关于强制转换的编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46647439/