gpt4 book ai didi

c - 修改并返回函数中的结构体

转载 作者:行者123 更新时间:2023-11-30 16:06:22 24 4
gpt4 key购买 nike

我正在创建一个游戏,它创建一个带有电线的二维 map ,每条电线都是一个房间。因此,我正在创建一个从绳索 (0,0) 开始的玩家,即我的游戏中的房间 1。我正在尝试归还握住电源线的播放器,这就是我的问题所在。返回类型“struct PC *”时,我得到了不兼容的类型,但预期是“struct PC”。

世界是我的二维 map ,每个房间都有绳索,而绳索就是玩家的绳索。

struct PC
{
int respect;
int x;
int y;

};

void createRooms(struct room AllRooms[])
{
int MaxRooms = 9;
int number = 1;
for(int i = 0;i < MaxRooms; i++)
{
AllRooms[i].roomNum = number;
number++;
}
for(int i = 0;i < MaxRooms; i++)
{
printf("%d",AllRooms[i].roomNum);
}

}

void createWorld(struct room AllRooms[], int rows, int cols, struct room World[rows][cols])
{
int counter = 0;
for(int i = 0; i <= rows;i++)
{
for(int j = 0; j <= cols; j++)
{
World[i][j] = AllRooms[counter];
counter++;
printf("\nWorld %d", World[i][j].roomNum);
}

}

}

struct PC startPointPC(struct PC* player,int rows, int cols, struct room* World[rows][cols],struct PC* cords[rows][cols])
{

int x = 0;
int y = 0;

player->x = x;
player->y = y;

cords[x][y] = player;
printf("\nYou are starting in Room %d",World[x][y]->roomNum);

return player;

}

int main()
{
int MaxRooms = 9;
int rows = 2;
int cols = 2;
//creaste each room
struct room Room1;
struct room Room2;
struct room Room3;
struct room Room4;
struct room Room5;
struct room Room6;
struct room Room7;
struct room Room8;
struct room Room9;
struct PC player;
player.respect = 40;

//Store them into a array
struct room AllRooms[MaxRooms];
AllRooms[0] = Room1;
AllRooms[1] = Room2;
AllRooms[2] = Room3;
AllRooms[3] = Room4;
AllRooms[4] = Room5;
AllRooms[5] = Room6;
AllRooms[6] = Room7;
AllRooms[7] = Room8;
AllRooms[8] = Room9;

//allrooms has all the 9 rooms in the array
createRooms(AllRooms);

struct PC player;
struct room World[rows][cols];
struct PC cords[rows][cols];

player = startPointPC(&player,rows,cols,&World,&cords);

}

最佳答案

cords 应该是指针数组,而不是结构数组。与世界相同。

不需要从 startPointPC 返回任何内容,因为它会就地修改结构。

将数组传递给函数时不要使用 &。数组用作函数参数时会自动转换为指针。

您的代码正在打印World[x][y]的内容,但从未初始化它。但是问题中没有任何 struct room 代码,我假设您只是为了简化而忽略了它。

void startPointPC(struct PC* player,int rows, int cols, struct room* World[rows][cols],struct PC* cords[rows][cols])
{

int x = 0;
int y = 0;

player->x = x;
player->y = y;

cords[x][y] = player;
printf("\nYou are starting in Room %d",World[x][y]->roomNum);
}

int main()
{
struct PC player;
struct room *World[rows][cols];
struct PC *cords[rows][cols];

startPointPC(&player,rows,cols,World,cords);
}

关于c - 修改并返回函数中的结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59978152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com