简体   繁体   English

何时使用指向C中嵌套结构中另一个结构的指针

[英]When to use a pointer to another struct in nested structs in C

I'm confused as when should I use a pointer to another struct or contain a copy. 我很困惑,因为我何时应该使用指向另一个结构的指针或包含副本。 For instance, should I use Products *prods; 例如,我应该使用Products *prods; or Products prods; Products prods; within Inventory? 在库存? and how do I malloc ? 我怎么选择malloc

typedef struct Products Products;
struct Products
{
    int  id;
    char *cat;
    char *name
};

typedef struct Inventory Inventory;
struct Inventory
{
    char* currency;
    int size;
    Products prods; // or Products *prods;
};

You should use a pointer when the size of the array is unknown at compile time. 在编译时未知数组大小时应使用指针。 If you know each Inventory struct will contain exactly one Products struct or 10 or 100, then just declare Products prods[100] . 如果您知道每个Inventory结构将只包含一个Products结构或10或100,那么只需声明Products prods[100] But if you're reading arbitrary records at runtime and can't know at compile time how many Products records an Inventory struct will contain, then use Products *prods . 但是,如果您在运行时读取任意记录并且无法在编译时知道Inventory结构将包含多少Products记录,则使用Products *prods You'll also need size and count struct elements to keep track of how much you've malloc'd or realloc'd and how much of that memory you've filled with Products structs. 您还需要sizecount结构元素来跟踪您对malloc或重新分配的内容以及您使用Products结构填充了多少内存。

Complementing Kyle's answer, the decision about whether or not using a pointer to Products , you must think of the following: 作为对Kyle的答案的补充,关于是否使用指向Products的指针的决定,您必须考虑以下事项:

If you don't know how many elements you'll have, your Inventory struct should have at least: 如果您不知道您将拥有多少元素,那么您的Inventory结构应该至少具有:

typedef struct Inventory Inventory;
struct Inventory
{
    char *currency;
    int size, count;
    Products* prods;
    ... // other elements you should need
};

and the pointer should be defined as (when instantiating an Inventory element): 并且指针应该定义为(在实例化Inventory元素时):

...
Inventory inv;
inv.size = _total_elems_you_will_need_
inv.prods = (Products *)malloc(inv.size * sizeof(Products));
...

On the other hand, if that amount is always fixed, then you can define your struct Inventory with something like this (instead of the pointer defined above): 另一方面,如果该数量总是固定的,那么你可以用这样的东西定义你的结构Inventory (而不是上面定义的指针):

Products prods;      // if you'll need only one element.
Products prods[10];  // if you'll need only ten.

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

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