2012-01-22 48 views
2

有人请向我解释如何正确使用strcmp函数?我创建一个井字棋游戏,我不断收到错误:正确使用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; 
} 
+6

'mark_location(int userU,char * str)' – wildplasser

+0

错误与您的类型有关。但是,在决定选择哪种移动方式时(例如,如果选择了无效移动会发生什么情况),您会有一些问题。你认为你可以把字符串变成一个枚举,然后运行一个switch语句吗? –

回答

1

在函数的参数,你都宣称“STR”为“字符”。它应该是“char *”。

3

你的函数声明更改为以下:

void mark_location(int userU, char *str) { 

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

还要确保你已经在你的文件的顶部包括string.h

#include <string.h> 
+0

我仍然得到相同的错误,它说我使用*操作符错误。 – user1064913

+0

你把'*'放在哪里? – Mat

+0

@ user1064913:查看我添加的信息。 –

1

strcmp需要一个指向字符数组,但str被宣布为一个字符,当它应该是char*

4

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

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返回到它,所以如果两个字符串相等,你会得到一个0也不是0是1

因此,工程节约万吨你的时间打字。