[英]Allocating array of structures with malloc
嗨,我有一個關於這個問題的問題(但是我沒有足夠的代表評論其中一個答案)。
在最上面的答案中,@ pmg表示,他說你需要做
student* students = malloc(numStudents * sizeof *students);
首先,這是否等於/簡寫為
student* students = malloc(numStudents * sizeof(*students));
如果是這樣,為什么您不執行sizeof(*students)
而不執行sizeof(student)
?
沒有人對此發表評論或喊他,所以我假設他在寫,請盡可能詳細地介紹兩者之間的區別。 我真的很想了解。
假設您不是在聲明聲明的同時初始化students
。 那么代碼將是:
students = malloc(numStudents * sizeof *students);
我們甚至不知道students
是哪種數據類型,但是我們可以說出它在錯誤地分配了正確的字節數。 因此,我們確定此行上沒有分配大小錯誤。
當然,這兩個版本分配的內存量相同,但是這一版本不太容易出錯。
在其他版本中,如果您在sizeof
使用了錯誤的類型,則可能會在一段時間內不會引起注意。 但是,在這個版本中,如果students
在左邊不符合students
的權利,它更可能你會發現這個問題,立竿見影。
http://en.wikipedia.org/wiki/Sizeof#Use
與變量和表達式一起使用時,可以在不帶括號的情況下使用sizeof。 表達方式
*students
正在取消指向學生結構的指針,因此
sizeof *students
將返回與
sizeof(student)
兩者之間沒有區別。 您也可以通過打印尺寸來自己檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.