gpt4 book ai didi

c - 正确使用strcmp函数?

转载 作者:行者123 更新时间:2023-12-04 09:12:09 26 4
gpt4 key购买 nike

有人可以向我解释如何正确使用 strcmp功能?我正在创建一个井字游戏,但我不断收到错误消息:

passing argument 1 of ‘strcmp’ makes pointer from integer without a cast

我创建了两个指针作为 strcmp 的参数。功能。一是玩家输入的输入,二是玩家选择的 Action 。但是,当我尝试运行代码时,出现上述错误。下面是我的一段代码:
void mark_location(int userU, char str) {
char *moves[] = {"upperLeft", "up", "upperRight", "left", "center", "right", "lowerLeft", "down", "lowerRight"};

if (strcmp(str, moves[0]) == 0)
board[0][0] = userU;
else if (strcmp(str, moves[1]) == 0)
board[0][1] = userU;
else if (strcmp(str, moves[2]) == 0)
board[0][2] = userU;
else if (strcmp(str, moves[3]) == 0)
board[1][0] = userU;
else if (strcmp(str, moves[4]) == 0)
board[1][1] = userU;
else if (strcmp(str, moves[5]) == 0)
board[1][2] = userU;
else if (strcmp(str, moves[6]) == 0)
board[2][0] = userU;
else if (strcmp(str, moves[7]) == 0)
board[2][1] = userU;
else if (strcmp(str, moves[8]) == 0)
board [2][2] = userU;
}

最佳答案

正如其他人已经指出的那样,第二个参数应该是 char* 类型。而不是 char .

我只想提一下 if 的系列语句可以重写为 for环形:

void mark_location(int userU, char* str) {
char *moves[] = {"upperLeft", "up", "upperRight", "left", "center", "right", "lowerLeft", "down", "lowerRight"};
int i;
for (i = 0; i < 9; i++) {
if (strcmp(str, moves[i]) == 0) {
board[i / 3][i % 3] = userU;
break;
}
}
}

重新初始化 moves 是否有意义也值得考虑。每次调用函数时,是否为 str 的无效值应该引发错误。

关于c - 正确使用strcmp函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8963742/

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