【问题标题】:Assignment makes pointer from int w/out a cast赋值使指针从 int 没有强制转换
【发布时间】:2013-06-19 02:38:47
【问题描述】:

我正在为一个记忆斐波那契数的程序编译一些代码。该程序运行良好,但是当我在 linux 环境中编译时,我在编译之前收到此警告。

line 61: warning: assignment makes pointer from integer without a cast [enabled by default]

这是此警告来自何处的代码的 sn-p,我将尝试展示最相关的内容,以获得最好的情况介绍

int InitializeFunction(intStruct *p, int n)

    p->digits = (int)malloc(sizeof(int) * 1);

        if(p->digits == NULL)
            handleError("Got error");

    //making the one index in p->digits equal to n
    p->digits[0] = n;

    //incrementing a field of 'p'
    p->length++;

    //return 1 if successful
    return 1;

这个函数只为了一个非常特定的目的被调用了两次。它用于初始化斐波那契序列 f[0] = 0 & f[1] = 1 中的两个基本情况。这就是它的唯一目的。因此,如果我通过引用传递结构数组中特定索引的地址,它只是应该初始化这些值:

Initializer(&someIntStruct[0], 0) ---->  after function -> someIntStruct[0] == 0
Initializer(&someIntStruct[1], 1) ---->  after function -> someIntStruct[1] == 1

想法?

【问题讨论】:

  • 1/ 永远不要从 malloc 中转换返回值(无论如何在 C 中)。 2/乘以一就是所谓的恒等运算,没有效果,完全没必要。 3/ 你返回 1 always 所以我不确定你是如何检测到失败的,除非handleError 退出你的程序。

标签: c arrays pointers casting integer


【解决方案1】:

改变

p->digits = (int)malloc(sizeof(int) * 1);

p->digits = (int*)malloc(sizeof(int) * 1);

【讨论】:

  • 不要在 C 中强制转换 malloc,你只是在 自找麻烦。
  • @paxdiablo 我在 Nobilis 的链接中看到了原因,这很有帮助。
【解决方案2】:

我怀疑警告与这一行有关:

p->digits = (int)malloc(sizeof(int) * 1);

由于 malloc 返回一个 void* ,而您将其转换为 int。我想p->digitsint*

尝试将其更改为:

p->digits = (int *)malloc(sizeof(int) * 1);

【讨论】:

    【解决方案3】:

    It's considered bad practice to cast the result of malloc.

    正如已经指出的那样,您也没有正确执行此操作(应该是 (int*) )。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多