mlbiche
mlbiche

Reputation: 97

When should a pointer to a structure should be use in a structure or not?

I'm wondering when I should use a pointer to a structure in a structure or not.

I clearly understand why we use a pointer to a structure in linked lists for example, but I'm facing an issue in another case.

For example:

#include <stdlib.h>
#include <string.h>

#define NICK_MAX_LENGTH 100

struct deck {
    size_t nb_cards;
    int *cards;
}

// Should I do :
struct player {
    int id;
    char nick[NICK_MAX_LENGTH];
    struct deck *pl_deck;
}

struct player* my_function1() {
    struct player *pl = malloc(sizeof(struct player));
    pl->id = 1;
    strcpy(pl->nick, "Paul")
    pl->pl_deck = malloc(sizeof(struct deck));
    pl->pl_deck->nb_cards = 3;

    for (int i = 0; i < 3; ++i)
        pl->pl_deck->cards[i] = i + 1;

    return pl;
}

// .. or should I do :
struct player {
    int id;
    char nick[NICK_MAX_LENGTH];
    struct deck pl_deck;
}

struct player* my_function2() {
    struct player *pl = malloc(sizeof(struct player));
    pl->id = 2;
    strcpy(pl->nick, "Matt")

    struct deck pl_deck;
    pl_deck.nb_cards = 3

    for (int i = 0; i < 3; ++i)
        pl_deck.cards[i] = i + 1;

    pl->pl_deck = pl_deck;

    return pl;
}

Upvotes: 2

Views: 84

Answers (2)

bipll
bipll

Reputation: 11940

Both options should work provided you write the parts you have not uncovered correctly.

But note that your deck is a small struct with very little storage overhead and, moreover, is uniquely owned by a player so composition would probably be a more realistic option, to eliminate all the complexities of pointer management.

(As long as you don't plan to reuse the decks, of course.)

Upvotes: 1

Barmar
Barmar

Reputation: 781058

Use a pointer if the lifetimes of the two structures need to be managed indepdendently. If you can have multiple players using the same deck, you need to use a pointer so they can both refer to it. Or if you need to be able to free the player while keeping their deck around, or vice versa, you should use a pointer.

On the other hand, if there's always a one-to-one correspondence between player and deck, you should nest the structures.

Upvotes: 5

Related Questions