[英]C - Struct- Integer to a pointer without cast
因此,當我為struct
的成員malloc
一個數組時,我很難弄清楚到底發生了什么? 出現以下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->bytes[i]
的類型為Byte
,它是“數組”中的單個元素。 malloc
調用返回一個指針 。
您不分配數組本身,而是嘗試分別分配每個元素,這不是它的工作原理。 除了編譯器消息外, n->bytes
可能無法指向有效位置,從而使取消引用n->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);
}
n->bytes[i]
實際上是*n->(bytes+i)
。 因此,您要將malloc
返回的內存地址分配為Byte類型,而不是指針類型。
值得指出的是,在下一行中,即使您只是嘗試為它分配一個地址,也要將0分配給n->bytes[i]
。 如果您試圖分配設置為0的內存,請使用calloc
它會為您分配內存並將其設置為0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.