【问题标题】:C - Struct- Integer to a pointer without castC - Struct- 指向没有强制转换的指针的整数
【发布时间】:2018-07-29 11:59:41
【问题描述】:

所以当我 malloc 一个数组是 struct 的成员时,我很难弄清楚发生了什么? 出现以下error 消息:

“赋值使指针变成整数而不进行强制转换”。

如果有人能帮我看看我在malloc 中哪里出错了,我们将不胜感激。

typedef struct _big_num {
   int  nbytes;  // size of array
   Byte *bytes;  /// array of Bytes
} BigNum;

void initBigNum(BigNum *n, int Nbytes)
{
    int i;
    n->nbytes = Nbytes;
    for (i = 0; i < Nbytes; i++) {
       n->bytes[i] = malloc(sizeof(Byte));   //This is where the error came up
       n->bytes[i] = 0;
       assert(n->bytes[i] == 0);
}
return;
}

【问题讨论】:

  • n-&gt;bytes[i] 是什么?您确定此索引存在(您有权访问它)吗?

标签: c pointers struct typedef


【解决方案1】:

n-&gt;bytes[i] 的类型为Byte,它是“数组”中的单个元素。 malloc 调用返回一个指针

您不分配数组本身,而是尝试分别分配每个元素,这不是它的工作原理。除了编译器消息之外,n-&gt;bytes 可能未指向有效位置,从而导致对 any 索引的取消引用 n-&gt;bytes[i] 无效。

你可能想要

void initBifNum(BigNum *n, int NBytes)
{
    // Initialize members and allocate memory for array
    n->nbytes = NBytes;
    n->bytes = malloc(sizeof *n->bytes * NBytes);

    // Initialize all elements in the array to zero
    memset(n->bytes, 0, sizeof *n->nbytes * NBytes);
}

【讨论】:

  • 用命令式写的句子,如“你不分配数组本身,而是尝试分配......”,有被误解为做某事的指令的风险。对于描述当前代码的部分,这将更清楚地写为声明性的,如“您在问题中显示的代码尝试分别分配每个元素。相反,您应该分配一个 Byte 对象数组并将指针 bytes 设置为指向它们的开头。”
  • 类似地,“n-&gt;bytes 可能未指向有效位置”这样的子句可以解释为禁止将n-&gt;bytes 设置为指向有效位置。
  • callocmalloc 后跟memset 更易于阅读且不易出错(并且可能更快)
【解决方案2】:

n-&gt;bytes[i] 真的是*n-&gt;(bytes+i)。因此,您将 malloc 返回的内存地址分配给类型 Byte 而不是指针。

值得指出的是,在下一行中,您将 0 分配给 n-&gt;bytes[i],即使您只是尝试为其分配地址。如果您尝试分配设置为 0 的内存,只需使用 calloc - 它会为您分配内存并将其设置为 0。

【讨论】:

  • 它是(n-&gt;bytes)[i]-&gt; 的语法是第二个操作数必须是标识符。 n-&gt;(X) 是语法错误,也没有任何意义。
猜你喜欢
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多