2013-05-12 67 views
0

我得到了大部分工作,包括随机化和洗牌,但是当涉及到分配正确的脸部/套装值时,我无法做到正确。此外,我正在'中止(核心转储)',可能是因为我几乎不知道我在做什么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 %s\n", i+1, shoe->faces[shoe[i].face], shoe->suits[shoe[i].suit]); 
} 

free(shoe); 

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

编辑:其他问题;我是否以适当的方式访问了我的结构成员'面孔'和'适合'?对我来说似乎是这样,但是再次,我看不到还有什么会导致我的字符串的奇怪输出(请参阅代码中的评论)。

另外,我可以将SHOE_SIZE作为我的数组的成员,并以相同的方式(鞋 - >变量)访问它,而不必先通过变量SHOE_SIZE分配它?

回答

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

这里你正在泄漏内存:shoe_p指出了一些mallocated记忆,但现在你失去了这个指针,因为你把它重新分配的指针的shoe的第一要素。我认为你根本不需要这两条线。

free(shoe); 

是错的太多:你没有使用malloc()创建shoe,所以你并不需要,切莫free()它。

probably because I have very little idea what I'm doing with malloc

右键,但不要担心:你可以通过阅读this提高你的知识。

+0

如何使用malloc创建鞋? – kensing 2013-05-12 16:12:20

+0

@kensing'shoe = malloc(sizeof(cards)* SHOE_SIZE);' – 2013-05-12 16:12:56

+0

(+1)for“mallocated” – 2013-05-12 16:13:15

1
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()它在和。

+0

宝贵的意见,但我仍然得到分段错误 – kensing 2013-05-12 16:37:06

+0

作为我注意到了这一刻,你的'malloc()'调用也没有意义。它必须是'malloc(sizeof(cards)* 1000);'或者我在你的源代码中理解错误吗? – 2013-05-14 21:09:52

+0

我只是确定有足够多的,但现在它是'malloc(sizeof(card)* SHOE_SIZE);' – kensing 2013-05-15 01:28:55