c-纸牌游戏问题-内存和奇数



我完成了大部分工作,包括随机化和混洗,但当涉及到分配正确的面部/西装值时,我无法正确处理。此外,我会被"中止(核心转储(",可能是因为我对malloc做什么一无所知(在这种情况下,如果有什么不同的话(。

typedef struct cards {
    char suits[4][9], faces[13][6];
    int suit, face, card;
} cards;
const int SHOE_SIZE = DECK_SIZE * numberOfDecks; // user given input, please disregard
cards shoe[SHOE_SIZE];
init_struct(&shoe);
cards *shoe_p = malloc(sizeof(cards) + 1000 * sizeof(int));
shoe_p = shoe;
int i;
for (i = 0; i < SHOE_SIZE; i++) {
    shoe[i].card = i;
    shoe[i].suit = shoe[i].card % 4;  // maybe one of these should be % and another /
    shoe[i].face = shoe[i].card % 13; // but when I try that, I get strings like "ace of ace"
    printf("card #%d = %s of %sn", i+1, shoe->faces[shoe[i].face], shoe->suits[shoe[i].suit]);
}
free(shoe);

我遗漏的代码部分无疑是所描述问题的来源。请让我知道我是否应该提供更多信息!

编辑:附加问题;我是否以正确的方式访问结构成员"faces"one_answers"suits"?对我来说似乎是这样,但话说回来,我看不出还有什么原因会导致我的字符串输出奇怪(请参阅代码中的注释(。

此外,我是否可以将SHOE_SIZE作为数组的成员,并以相同的方式访问它(SHOE->变量(,而不必首先通过变量SHOE_SIZE进行分配?

cards *shoe_p = malloc(sizeof(cards) + 1000 * sizeof(int));
shoe_p = shoe;

在这里,您正在泄漏内存:shoe_p指向了一些有缺陷的内存,但现在您丢失了该指针,因为您将其重新分配给了指向shoe的第一个元素的指针。我认为你根本不需要这两行字。

free(shoe);

也是错误的:您没有使用malloc()创建shoe,所以您不需要也决不能使用free()

可能是因为我不知道我在用malloc 做什么

是的,但别担心:你可以通过阅读这篇文章来提高你的知识。

const int SHOE_SIZE = DECK_SIZE * numberOfDecks;
cards shoe[SHOE_SIZE];

这些台词一点道理都没有。第一行在运行时计算(即使是用户给定的输入(一个常数。因此,在编译它的值时还不知道。但在下一行中,您将使用这个未知数字在编译时分配非动态内存。因此,如果你想正确地做到这一点,就把第二行去掉,使用malloc()(正如你在下面几行中正确地做的那样(。此外,您正在使用shoe_p = shoe;行丢弃此内存。解决这个问题的正确方法是:

...
const int SHOE_SIZE = DECK_SIZE * numberOfDecks;
cards *shoe = malloc(sizeof(cards) + 1000 * sizeof(int));
init_struct(&shoe);
int i;
...

因为您使用的是malloc(),所以在和处使用free()是绝对正确的。

最新更新