c - 正确使用strcmp函数?

标签 c strcmp

有人可以向我解释如何正确使用 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/

相关文章:

在 SHA-2 算法中将 long 转换为 unsigned char

c - 将结构数组传递给函数

c - c中的strcmp字符串和字符数组

c - 如何在不要求用户输入的情况下找到一个数字的出现频率?

c - Malloc、Calloc 用于测试我的内存极限

C++;如何比较遍历相同字符串 vector 的不同迭代器的字符串值

c - strcmp 只返回 0(回文算法错误)

C:比较结构中的两个字符串

c - 如何正确比较 C 中的字符串?

c - 检查数组所有元素的函数