简体   繁体   English

用malloc分配结构数组

[英]Allocating array of structures with malloc

C - initialize array of structs C-初始化结构数组

Hi, I have a question about this question (but I don't have enough rep to comment on one of the answers). 嗨,我有一个关于这个问题的问题(但是我没有足够的代表评论其中一个答案)。

In the top answer, the one by @pmg, he says you need to do 在最上面的答案中,@ pmg表示,他说你需要做

student* students = malloc(numStudents * sizeof *students);

Firstly, is this equivalent to/shorthand for 首先,这是否等于/简写为

student* students = malloc(numStudents * sizeof(*students));

And if so, why do you do sizeof(*students) and not sizeof(student) ? 如果是这样,为什么您不执行sizeof(*students)而不执行sizeof(student)

No one commented or called him out on it so I'm assuming he's write, and PLEASE go into as much detail as possible about the difference between the two. 没有人对此发表评论或喊他,所以我假设他在写,请尽可能详细地介绍两者之间的区别。 I'd really like to understand it. 我真的很想了解。

Let's say you were not initializing students at the same time you declared it; 假设您不是在声明声明的同时初始化students then the code would be: 那么代码将是:

students = malloc(numStudents * sizeof *students);

We don't even know what data type students is here, however we can tell that it is mallocking the right number of bytes. 我们甚至不知道students是哪种数据类型,但是我们可以说出它在错误地分配了正确的字节数。 So we are sure that there is not an allocation size error on this line. 因此,我们确定此行上没有分配大小错误。

Both versions allocate the same amount of memory of course, but this one is less prone to errors. 当然,这两个版本分配的内存量相同,但是这一版本不太容易出错。

With the other version, if you use the wrong type in your sizeof it may go unnoticed for a while. 在其他版本中,如果您在sizeof使用了错误的类型,则可能会在一段时间内不会引起注意。 But in this version, if students on the left does not match students on the right, it is more likely you will spot the problem straight away. 但是,在这个版本中,如果students在左边不符合students的权利,它更可能你会发现这个问题,立竿见影。

http://en.wikipedia.org/wiki/Sizeof#Use http://en.wikipedia.org/wiki/Sizeof#Use

You can use sizeof with no parentheses when using it with variables and expressions. 与变量和表达式一起使用时,可以在不带括号的情况下使用sizeof。 the expression 表达方式

*students 

is derefencing a pointer to a student struct, so 正在取消指向学生结构的指针,因此

sizeof *students 

will return the same as 将返回与

sizeof(student)

There is no difference between the two. 两者之间没有区别。 You can check it by yourself also by printing their sizes. 您也可以通过打印尺寸来自己检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM