2017-11-25 21 views
0

私の機能には助けが必要ですが、これは私が行ったことです。ポインタの配列内の要素を交換する方法

void ShuffleCards(int (*deck_of_cards)[NUM_CARDS]) 
{ 

    int i = 51; 
    int j, temp; 
    while(i>0) 
    { 
     j = rand()%(i+1); 
     temp = *deck_of_cards[i]; 
     *deck_of_cards[i] = *deck_of_cards[j]; 
     *deck_of_cards[j] = temp; 
     i--; 
    } 
} 

私はスワッピングが発生する前に適切にコード化する必要がある何が不明だから、私はセグメンテーションフォールトを取得されています。お願い助けて。

+0

ようこそ。 [ヘルプページ](http://stackoverflow.com/help)、特に[ここではどのトピックを聞くことができますか?](http://stackoverflow.com/help/)のセクションを読んでください。 on-topic)と[[どのような種類の質問を避けるべきですか?]](http://stackoverflow.com/help/dont-ask)を参照してください。また、[ツアーを受けてください](http://stackoverflow.com/tour)と[良い質問をする方法を読む](http://stackoverflow.com/help/how-to-ask)もご覧ください。最後に、[最小限の完全で検証可能な例](http://stackoverflow.com/help/mcve)の作成方法を学んでください。 –

答えて

1

カードのデッキを表現するためにint配列を使用していて、その配列をシャッフルしたいとします。まず、デッキ内に配列サイズを指定しないでください。 NUM_CARDSを仮定= 52、

void ShuffleCards(int *deck_of_cards) 
{ 
    int i = NUM_CARDS - 1; //it is better to initialize i in term of NUM_CARDS 
    int j, temp; 
    while(i>0) 
    { 
     j = rand()%(i+1); //gives 0 to i 
     temp = deck_of_cards[i]; 
     deck_of_cards[i] = deck_of_cards[j]; 
     deck_of_cards[j] = temp; 
     i--; 
    } 
} 

あなたの呼び出し元の関数は次のようなものになります:stackoverflow.comに

int deck_of_cards[NUM_CARDS]; 

//do something to initialize your deck 

ShuffleCards(deck_of_cards); 

//do something with the shuffled deck; 
+0

良い参考文献は[Fisher YatesのシャッフルアルゴリズムC](https://stackoverflow.com/questions/42321370/fisher-yates-shuffling-algorithm-in-c)で、その答えの元のSO質問へのリンクを参照してください。 –

関連する問題