【发布时间】:2017-04-24 21:10:44
【问题描述】:
我想知道什么时候应该在结构中使用指向结构的指针。
例如,我清楚地理解为什么我们在链表中使用指向结构的指针,但在另一种情况下我遇到了问题。
例如:
#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 和不满意的例子会有所帮助。
标签: c pointers struct structure