char数组初始值设定项中的多余元素

时间:2015-09-30 11:40:57

标签: c arrays

我试图提高我糟糕的C技能,所以我正在编写一个tic tac toe程序。它只是在它的第一步,但我希望能够在进入游戏本身的整个算法之前打印一块板。我计划将1用于x,将0用于圆圈,以便以后能够使用和。 我正在使用gcc(ubuntu)并收到此错误:

xo.c:11:3: error: (near initialization for ‘board[0]’)
xo.c:11:3: error: excess elements in char array initializer
xo.c:11:3: error: (near initialization for ‘board[0]’)
xo.c:11:3: error: excess elements in char array initializer
xo.c:11:3: error: (near initialization for ‘board[1]’)
xo.c:11:3: error: excess elements in char array initializer
xo.c:11:3: error: (near initialization for ‘board[1]’)
xo.c:11:3: error: excess elements in char array initializer
xo.c:11:3: error: (near initialization for ‘board[2]’)
xo.c:11:3: error: excess elements in char array initializer
xo.c:11:3: error: (near initialization for ‘board[2]’)

我想为电路板启动一个3x3的二维数组。我不明白为什么会有多余的,我初始化了[3] [3]并输入了9个元素。这是我写的代码:

#include<stdio.h>

/***** Create two dimensional array full of blank spaces
    1 marks the X , 0 marks the circle.
    Let use enter coordinates (line and coloumn) for placing the 1 (x) and automatically print the board with the computers' move.
*****/ 
int i = 0;
int j = 0;
void main() {
    char board[3][3] = {
        {" " , " " , " "} , {" " , " " , " "} , {" " , " " , "t"}
    };
    for(i=0 ; i<3 ; i++) {
        for(j=0 ; j<3 ; j++) {
            printf("%c " , board[i][j]);
        }
        printf("\n");
    }
}

1 个答案:

答案 0 :(得分:4)

" "是一个字符串(char *)字面值。对于单个' ',您需要char

变化:

    char board[3][3] = {
        {" " , " " , " "} , {" " , " " , " "} , {" " , " " , "t"}
    };

为:

    char board[3][3] = {
        {' ' , ' ' , ' '} , {' ' , ' ' , ' '} , {' ' , ' ' , 't'}
    };