我想知道什么时候应该使用指向结构体的结构体的指针。何时应该在结构中使用指向结构的指针?
我清楚地理解了为什么我们在链表中使用指向结构的指针,但我在另一个案例中遇到了问题。
例如:
#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;
}
欢迎来到StackOverflow。 请参考参考stackoverflow.com/tour, 学习问好问题stackoverflow.com/help/how-to-ask, 作出一个MCVE stackoverflow.com/help/mcve 不清楚你的问题是什么,或者你的代码有什么问题。也许一个完整的MCVE和不满意的例子会有所帮助。 – Yunnosch