[英]Memset function in C initialised all the arrays
我試圖初始化一個由指針組成的數組:
我使用的代碼是:
int c = 15;
Struct *Pointer[c] = {NULL};
memset( pointer, 0, c *sizeof(pointer) );
它起作用了,但是這個 memset() function 不僅初始化了我的指針數組,還初始化了我所有的其他 arrays ...
有什么辦法可以解決嗎?
我不能使用 for(){} 或 while function 因為它會增加我的時間復雜性......
干杯'
sizeof(pointer)
是整個數組pointer
的大小。 將大於 1 的整數乘以 size 到memset()
將導致超出范圍的訪問。
去除有害的乘法。
int c = 15;
Struct *Pointer[c] /* = {NULL} */; /* VLA cannot be initialized */
/* some other code that uses Pointer */
memset(Pointer, 0, sizeof(Pointer));
memset(Pointer, 0, sizeof(Pointer));
或者
memset(Pointer, 0, c * sizeof(*Pointer));
指出不同。
如果您進行一些研究並打印出sizeof(Pointer)
並計算出c * sizeof(Pointer)
錯誤的原因,您可以自己回答您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.