C - 结构 - 不进行强制转换的整数到指针

标签 c pointers struct typedef

所以,当我 malloc 一个属于 struct 成员的数组时,我在弄清楚发生了什么时遇到了一些麻烦? 出现以下错误消息:

"assignment makes integer from pointer without a cast".

如果有人能帮我看看我在 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->bytes[i] 的类型为 Byte,它是“数组”中的单个元素。 malloc 调用返回一个指针

您不分配数组本身,而是尝试单独分配每个元素,这不是它的工作方式。除了编译器消息之外,n->bytes 可能不会指向有效位置,从而使取消引用 n->bytes[i] 对于 any 无效> 索引。

你可能想要

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);
}

关于C - 结构 - 不进行强制转换的整数到指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51580124/

相关文章:

c++ - C++中的初始化结构错误

将原始加速度计值转换为 12 位数字

c++ - 在父窗口中限制可拖动的子窗口?

c++ - 同一类不同方法中指针的 vector

C 结构错误 : Stack Smashing Detected, 中止(核心转储)

c - 获取排序数组中每个单词的计数

c - Apache httpd-2.4.9 编译错误

c - freeaddrinfo 上发生了什么事?

c - 读写矩阵

c++ - 函数的指针参数