Search code examples
carraysstringtic-tac-toe

Initialize 2d char array in c - tic tac toe game


I'm getting confused while trying to make the tic tac toe game in c. I'm following a book that uses a single char array of 8 elements to create the board. I know an array[8] contains 9 elements, but if the array is declared as char array, since it has to contain spaces to make the empty board for the game, shouldn't it be array[9], since it has to contain the 9 characters plus a null character '\0'? I'm having the same doubt when converting the board to a 2d array, since I understand the board should be made with an array[3][3], but if I want to declare it as char, where is the place for the null character?


Solution

  • The terminating zero is needed if a character array is used to store strings.

    In the case of your task there is no need to store strings in the array.

    So in C you may declare for example a 3*3 array the following way

    char board[3][3] =
    {
       "   ", // three spaces
       "   ",
       "   "
    };
    

    Each element of the array will not contain the terminating zero though it is initialized by a string literal.

    On the other hand you can include the terminating zero in each element if you think that it will be simpler to output such an array. In this case the array should be defined like

    char board[3][4] =
    //           ^^^
    {
       "   ", // three spaces
       "   ",
       "   "
    };
    

    As for your statement that

    an array[8] contains 9 elements

    then the array is declared as having exactly eight elements. :) I think you mean string literals. For example string literal "Hi" in C has type char[3] due to the terminating zero that is stored in the literal.