2013-05-12 49 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