1

strcmp関数の正しい使い方を教えてもらえますか?三目並べゲームを作成していますが、エラーが発生し続けます。

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

関数のパラメーターとして機能する2つのポインターを作成しましたstrcmp。1つはプレーヤーが入力する入力で、もう1つはプレーヤーが持つ動きの選択です。ただし、コードを実行しようとすると、上記のエラーが発生します。以下は私のコードの一部です:

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

他の人がすでに指摘しているように、2 番目の引数は型ではなく型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エラーが発生するかどうかも検討する価値があります。

于 2012-01-22T19:13:19.157 に答える
3

関数宣言を次のように変更します。

void mark_location(int userU, char *str) {

char(1 文字) から(文字列) への変更に注意してください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 に答える