1

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

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

我创建了两个指针作为strcmp函数的参数。一是玩家输入的输入,二是玩家选择的动作。但是,当我尝试运行代码时,出现上述错误。下面是我的一段代码:

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

5 回答 5

4

正如其他人已经指出的那样,第二个参数应该是 typechar*而不是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应该引发错误也可能值得考虑。

于 2012-01-22T19:13:19.157 回答
3

将您的函数声明更改为以下内容:

void mark_location(int userU, char *str) {

注意从char(单个字符)到char *(字符串)的变化。

还要确保您已string.h在文件顶部包含:

#include <string.h>
于 2012-01-22T19:08:24.963 回答
1

在函数参数中,您已将“str”声明为“char”。它应该是“char*”。

于 2012-01-22T19:08:09.723 回答
1

strcmp需要一个指向字符数组的指针,但str在应该是 . 时被声明为单个字符char*

于 2012-01-22T19:09:01.237 回答
0

尝试这样做:

for (i = 0; i < 9; i++) {
    if (!strcmp(*str, *moves[i]) ) {
        board[i / 3][i % 3] = userU;
        break;
    }
}

节省打字工作的另一件事:

strcmp()当字符串匹配时返回 0,因此在控制语句中写入时更喜欢写入

if(!strcmp(hello, world)){/* do this do that*/}.....1

而不是写

if(strcmp(hello, world)==0){/* do this do that*/}......2

在第一个等式中,if 语句对strcmp返回的任何内容执行 NOT,因此如果字符串相等,您将得到 0 而 NOT 0 是 1

因此,它可以节省您大量的打字时间。

于 2012-01-23T02:00:29.863 回答