指针未设置为结构数组的元素

时间:2017-01-05 09:47:07

标签: c pointers struct

需要帮助了解我做错了什么。这是我通过远程学习做的任务的一部分。感谢。

我正在传递一个指针和一系列玩家(2名玩家)。玩家是结构的地方:

#include<bits/stdc++.h>
using namespace std;


int main()
{
    int n,i,j,k,num = 0;
    cin >> n;
    int arr[n+1];
    for(i = 1;i <= n;++i)cin >> arr[i];
    for(i = 1;i <= n;++i)
    {
        if(i != arr[i])// condition to check if an element is in a cycle r nt
        {
            j = arr[i];
            arr[i] = 0;
            while(j != 0)// Here i am traversing a cycle as mentioned in 
            {             // first answer
                k = arr[j];
                arr[j] = j;
                j = k;
                num++;// reducing cycle by one node each time
            }
            num--;
        }
    }
    for(i = 1;i <= n;++i)cout << arr[i] << " ";cout << endl;
    cout << num << endl;
    return 0;
}

然后我尝试将指针(curplayer)设置为赢得随机化滚动的玩家。我正在逐步使用GDB,并且可以在命令之后确认该值是相同的。请帮忙!解释我做错了什么:

 struct player
{
        char name[NAMELEN + 1];
        int score; /* count of number of pieces on the board */
        colour token_colour;
};

struct player * play_game(struct player players[])
{
        gameboard board;
        struct player * current, *other;

        gameboard_init(board);
        player_init(&players[0],1);
        player_init(&players[1],2);

        **randomize_game(players,current);**

        /* replace this NULL return value with the appropriate return value */
        return NULL;
}

}

由于

1 个答案:

答案 0 :(得分:0)

您想要修改current,但curplayer是指向randomize_game的本地指针,它仅使用current中的值进行初始化。您对其所做的任何更改都不会应用于current中的play_game

如果要修改调用上下文中的任何变量,则需要传递其地址。这也适用于指针。

void randomize_game(struct player players[],struct player **curplayer)
{
        int p;
        time_t t;

        srand((unsigned) time(&t));
        p = rand() % 2;
        if(p==0){
                *curplayer= &players[0];
                players[0].token_colour = CC_WHITE;
                players[1].token_colour = CC_RED;
        }else{
                *curplayer= &players[1];
                players[0].token_colour = CC_RED;
                players[1].token_colour = CC_WHITE;
        }
}

当然,您需要更改传递变量的方式:

randomize_game(players, &current);