4

我正在尝试使用两个整数访问多维数组的值。该数组在另一个源文件中声明。我在问题源文件的顶部使用了外部声明。

在声明它的文件中,我可以访问这些值。但是,当我复制并粘贴同一行代码时,编译器会通知我表达式必须是指向完整对象类型的指针。

我是 C 和指针的新手,所以我真的不知道发生了什么。我会很感激任何想法。

extern struct piece board[8][8];


void move()
{
    
    char row;
    int column;
    int rowNumber = 0;
    printf("row: ");
    scanf("%c",&row);
    fflush(stdin);
    printf("column: ");
    scanf("%d",&column);
    column--;
    switch(row)
    {
    case 'A': rowNumber = 0; break;
    case 'B': rowNumber = 1; break;
    case 'C': rowNumber = 2; break;
    case 'D': rowNumber = 3; break;
    case 'E': rowNumber = 4; break;
    case 'F': rowNumber = 5; break;
    case 'G': rowNumber = 6; break;
    case 'H': rowNumber = 7; 
    }
    printf("\n your row is %d and column is %d",rowNumber,column);
    

     struct piece temp = &board[rowNumber][column];
    
}

和数组本身:

struct piece board[8][8] = {{{0,0,blackRook,"Rook"},{0,1,blackKnight,"Knight"},         {0,2,blackBishop,"Bishop"},{0,3,blackQueen,"Queen"},{0,4,blackKing,"King"}, {0,5,blackBishop,"Bishop"},{0,6,blackKnight,"Knight"},{0,7,blackRook,"Rook"}},
          {{1,0,blackPawn,"Pawn"}, {1,1,blackPawn,"Pawn"},{1,2,blackPawn,"Pawn"},{1,3,blackPawn,"Pawn"},{1,4,blackPawn,"Pawn"},{1,5,blackPawn,"Pawn"},{1,6,blackPawn,"Pawn"},{1,7,blackPawn,"Pawn"}},
                            {0},{0},{0},{0},


                             {{6,0,whitePawn,"Pawn"},{6,1,whitePawn,"Pawn"},{6,2,whitePawn,"Pawn"},{6,3,whitePawn,"Pawn"},{6,4,whitePawn,"Pawn"},{6,5,whitePawn,"Pawn"},{6,6,whitePawn,"Pawn"},{6,7,whitePawn,"Pawn"}},
                            {{7,0,whiteRook,"Rook"},{7,1,whiteKnight,"Knight"},{7,2,whiteBishop,"Bishop"},{7,3,whiteQueen,"Queen"},{7,4,whiteKing,"King"},{7,5,whiteBishop,"Bishop"},{7,6,whiteKnight,"Knight"},{7,7,whiteRook,"Rook"}}};

抱歉格式化,它在 Visual Studio 中看起来更好。前两个和最后两个数组都填充了结构块 - 其余为 0。空值似乎不会在我的代码中的其他任何地方引起任何问题。

编辑 - 这是件定义:

struct piece
{
    int row;
    int column;
    int weight;
    char name[20];

};
4

4 回答 4

3

除了&board[r][c]是类型struct piece *而不是类型之外,struct piece您还需要包含定义piece. 编译器告诉您它没有足够的关于struct piece.

于 2012-06-11T09:45:43.937 回答
1

我猜你的错误发生在这里:

struct piece temp = &board[rowNumber][column];

你忘记了 * 后面的部分

struct piece* temp = &board[rowNumber][column];

应该管用。

您还应该包括定义片段结构的标题。

于 2012-06-11T09:42:23.360 回答
0

下面的行是不正确的。temp 根本不是指针变量。

struct piece temp = &board[rowNumber][column]; 

如果您只想为数组的一个元素提供一个指针,那么

struct piece *temp = &board[rowNumber][column]; 

如果要为整个二维数组创建一个指针,那么它应该是

struct piece (*temp)[][8] = &board; 
于 2012-06-11T09:37:59.543 回答
0

Extern 是不够的,您还必须包含声明结构的 .h 。

于 2018-10-25T20:26:15.070 回答