如何交换指针数组中的元素

时间:2017-11-25 02:27:52

标签: c arrays pointers

我需要帮助我的功能,这就是我所做的。

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--;
    }
}

我遇到了分段错误,因为我不确定在交换发生之前必须正确编码的是什么。请帮帮我。

1 个答案:

答案 0 :(得分: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--;
    }
}

您的通话功能应如下所示:

int deck_of_cards[NUM_CARDS];

//do something to initialize your deck

ShuffleCards(deck_of_cards);

//do something with the shuffled deck;