【问题标题】:Proper use of the strcmp function?正确使用strcmp函数?
【发布时间】:2012-01-22 19:04:41
【问题描述】:

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

【问题讨论】:

  • mark_location(int userU, char *str)
  • 错误与您的类型有关。但是,您在选择选择哪一招时存在一些问题(例如,如果选择了无效的招,会发生什么?)。您认为您可以将字符串转换为枚举然后运行 ​​switch 语句吗?

标签: c strcmp


【解决方案1】:

正如其他人已经指出的那样,第二个参数的类型应该是 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 的无效值是否应该引发错误。

【讨论】:

    【解决方案2】:

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

    void mark_location(int userU, char *str) {
    

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

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

    #include <string.h>
    

    【讨论】:

    • 我仍然收到同样的错误,它说我使用 * 运算符错误。
    • 我把 * 放在你告诉我的地方,在 str 之前。仍然收到相同的消息,我包含了 string.h
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        尝试这样做:

        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

        所以它可以节省您大量的打字时间。

        【讨论】:

          猜你喜欢
          • 2014-11-03
          • 2021-04-27
          • 2022-08-16
          • 1970-01-01
          • 1970-01-01
          • 2013-11-05
          • 1970-01-01
          • 1970-01-01
          • 2013-05-09
          相关资源
          最近更新 更多