所以,当我 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/