gpt4 book ai didi

c - 关于 cast 的编译器警告

转载 作者:太空狗 更新时间:2023-10-29 11:49:24 25 4
gpt4 key购买 nike

我正在测试如下示例代码,为什么我在 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 

您正在将 mallocNULL 的返回比较结果分配给 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)

甚至更好(是的,不需要乘以始终为 1 的 sizeof(char))

关于c - 关于 cast 的编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46647439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com