简体   繁体   English

指针而不是结构体名称的含义是什么?

[英]What does a pointer instead a name in a struct of a struct mean?

What does *rooms[10] mean in this code? * room [10]在此代码中是什么意思? isn't it usually struct Room ? 通常不是struct Room吗? What does it mean in this case? 在这种情况下是什么意思?

struct Room
{
     float width;
     float length;
     float height;
     char *name;
};

struct House
{
     char* address;
     struct Room *rooms[10];
};
struct Room *rooms[10];

Per cdecl.org : 每个cdecl.org

declare rooms as array 10 of pointer to struct Room 将房间声明为指向struct Room的指针的数组10

This would be used when a House may contain up to 10 Rooms, each of which are allocated elsewhere, using null pointers to represent "unused" slots in the array. 当一栋房屋最多可容纳10个房间(每个房间都分配在其他位置)时,将使用此指针,这些房间使用空指针表示阵列中的“未使用”插槽。

In

struct House
{
     char* address;
     struct Room rooms[10];
};

you have 10 full instances of a Room . 您有一个Room 10个完整实例。 That is your House structure size is 10 times the size of the Room structure plus some extra (for the address ). 这是你的House结构尺寸是尺寸10倍Room结构加上一些额外的(对于address )。 Also, all 10 of these are in nearby locations in memory, causing higher fragmentation. 同样,所有这10个都位于内存中的附近位置,从而导致更高的碎片化。

On the other hand, in 另一方面,在

struct House
{
     char* address;
     struct Room *rooms[10];
};

you only have to store pointers to 10 rooms (which need to be allocated on the heap). 您只需要存储指向10个房间的指针(需要在堆上分配)。 In the first case when you call a function with House as parameter your stack is blown up because it needs a huge structure to be stored there while on the second case a much smaller structure is copied, resulting in faster function calls. 在第一种情况下,使用House作为参数调用函数时,堆栈被炸毁,因为它需要在其中存储巨大的结构,而在第二种情况下,复制的结构要小得多,从而可以更快地调用函数。

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

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