简体   繁体   中英

“error: subscripted value is neither array nor pointer nor vector”, but why?

I am writing a Tic-Tac-Toe program and am writing a function for the player's turn. I am passing in the Tic-Tac-Toe board (a 3x3 array) in the form of the pointer, b . The only problem is that on the last line I get the error in the title.

Subscripted value is neither array nor pointer nor vector: b[PlayerCoordsX][PlayerCoordsY] = "x";

Just for testing I've tried multiple different = values. Both characters and numerical values do not fix the issue.

Here is the abbreviated code with (what I hope) are the relevant bits:

void PlayerTurn(int *b);

...

int main(void)
{
    int Board[2][2];
    int (*b)[2][2];
    b = &Board;

    ...

    void PlayerTurn(int *b);

    ...

return 0;
}

void PlayerTurn(int *b)
{
    int PlayerCoordsX, PlayerCoordsY;

    while ((PlayerCoordsX != 1 || PlayerCoordsX != 2 || PlayerCoordsX != 3) && (PlayerCoordsY != 1 || PlayerCoordsY != 2 || PlayerCoordsY != 3))
    {
        printf("Enter the X coordinate you would like to use:");
        scanf("%i", &PlayerCoordsX);
        PlayerCoordsX = PlayerCoordsX - 1;

        printf("Enter the Y coordinate you would like to use:");
        scanf("%i", &PlayerCoordsY);
        PlayerCoordsX = PlayerCoordsY - 1;
    }

    b[PlayerCoordsX][PlayerCoordsY] = "x";
}

Your argument b is a pointer to an integer. This means that b[PlayerCoordsX] is an integer, and thus b[PlayerCoordsX][PlayerCoordsY] is basically trying to use an int (the "subscripted value") as a an array.

When you pass a 2D array to a function, the compiler needs to know the number of columns in the array. This is because an array is laid out as a linear block of memory and the compiler needs to calculate the index in that linear array.

So you need to pass

void PlayerTurn(int b[][2])
{
}

But it would be a good idea to #define the size, instead of using a 'magic' value 2 .

Since b is a pointer to int,

b[PlayerCoordsX]

is an integer, you cannot subscript b[PlayerCoordsX] . You need a pointer to pointer to int:

int **b;

then you can do double indirection. Or, if you have a flat array, calculate an index instead of using double indices:

b[PlayerCoordsY * numCols + PlayerCoordsX] = "x";

If you define the board like you do:

int board[3][3];

then you can change the function signature to:

void PlayerTurn(int b[][3])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM