1

I'm confused as when should I use a pointer to another struct or contain a copy. For instance, should I use Products *prods; or Products prods; within Inventory? and how do I 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;
};

2 Answers 2

2

Complementing Kyle's answer, the decision about whether or not using a pointer to Products, you must think of the following:

If you don't know how many elements you'll have, your Inventory struct should have at least:

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 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):

Products prods;      // if you'll need only one element.
Products prods[10];  // if you'll need only ten.
Sign up to request clarification or add additional context in comments.

3 Comments

And if you use malloc, don't forget to do: #include <stdlib.h>, and also test if its result has been NULL
Thanks, one more question, so I don't need to malloc Inventory, only Products, is that right?
You should need to malloc Inventory in the same sense Products does: if you'll need more than one Inventory object. You may think of this as if they were arrays...
1

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]. 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. 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.

2 Comments

Thanks, I'm wondering, wouldn't count and size be the same? I guess I'm not sure why I need count.
->size would be the size of the malloc'd space as measured in structs. ->count would be the amount of space used, starting at 0 and incremented as you read product records and filled the space. When ->count == ->size you need to realloc the pointer to get more space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.