TicTacToe classic in CRecursive and flexible approach to Tic-Tac-ToeFirst OOP TicTacToe gameTicTacToe game in RubyTic Tac Toe dynamically changing board position and score board positionTicTacToe Win CheckingCallback-oriented Tic-Tac-ToeTic Tac Toe - Verifying a player wonPython TicTacToeConsole TicTacToe implementationBeginner TicTacToe

What does the pair of vertical lines in empirical entropy formula mean?

Do you need to let the DM know when you are multiclassing?

Can we completely replace inheritance using strategy pattern and dependency injection?

Prob. 5, Sec. 6.2, in Bartle & Sherbert's INTRO TO REAL ANALYSIS, 4th ed: How to show this function is strictly decreasing using derivative

bash vs. zsh: What are the practical differences?

C++ logging library

The origin of the Russian proverb about two hares

What is the color of artificial intelligence?

Why is long-term living in Almost-Earth causing severe health problems?

Was planting UN flag on Moon ever discussed?

Why is Na5 not played in this line of the French Defense, Advance Variation?

Difference between prepositions in "...killed during/in the war"

Ability To Change Root User Password (Vulnerability?)

Grep Match and extract

empApi with Lightning Web Components?

How do i export activities related to an account with a specific recordtype?

Analogy between an unknown in an argument, and a contradiction in the principle of explosion

Math cases align being colored as a table

Can you make an identity from this product?

Is it possible to have 2 different but equal size real number sets that have the same mean and standard deviation?

Java Servlet & JSP simple login

Why are MBA programs closing in the United States?

Is there a set of positive integers of density 1 which contains no infinite arithmetic progression?

A map of non-pathological topology?



TicTacToe classic in C


Recursive and flexible approach to Tic-Tac-ToeFirst OOP TicTacToe gameTicTacToe game in RubyTic Tac Toe dynamically changing board position and score board positionTicTacToe Win CheckingCallback-oriented Tic-Tac-ToeTic Tac Toe - Verifying a player wonPython TicTacToeConsole TicTacToe implementationBeginner TicTacToe






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3












$begingroup$


I'm learning myself C and to make sure that I learn to code C in a proper way I created tic tac toe and want to hear your opinion on what I should do and what I shouldn't do.



One thing is sure is to divide the code up in several files maybe but outside of that.



The code:



#include <stdio.h>
#include <stdlib.h>

#define ROWS 3
#define BOARD_SIZE ROWS * ROWS

typedef enum false, true bool;

bool enter_entry(char *board, char character, int x, int y);
void print_board(const char *board);
void *init_board();
bool is_solved(char *board, char item);
bool is_draw(char *board);
bool is_equal(char *board, int indexA, int indexB, int indexC, char item);
void player_selection(char *board, char item);
void game_loop(char *board);

int main()

char *board = init_board();
game_loop(board);
return 0;


void *init_board()

char *board = malloc(sizeof(char) * BOARD_SIZE);
for(int i = 0; i < BOARD_SIZE; i++)

board[i] = ' ';

return board;


void print_board(const char *board)

for(int i = 1; i < BOARD_SIZE+1; i++)
%c ", board[i-1]);
if(i % 3 == 0)
n");


printf("n");


bool is_solved(char *board, char item)

if(is_equal(board, 0, 1, 2, item)) return true;
if(is_equal(board, 3, 4, 5, item)) return true;
if(is_equal(board, 6, 7, 8, item)) return true;

if(is_equal(board, 0, 3, 6, item)) return true;
if(is_equal(board, 1, 4, 7, item)) return true;
if(is_equal(board, 2, 5, 8, item)) return true;

if(is_equal(board, 0, 4, 8, item)) return true;
if(is_equal(board, 2, 4, 6, item)) return true;
return false;


bool is_draw(char *board)

for(int i = 0; i < BOARD_SIZE; i++)

if(board[i] == ' ')

return false;


return true;


bool is_equal(char *board, int indexA, int indexB, int indexC, char item)

if(board[indexA] == item && board[indexB] == item && board[indexC] == item)

return true;

return false;


bool enter_entry(char *board, char character, int x, int y)

int index = x + ROWS * y;

if(board[index] != ' ')

return false;


board[index] = character;
return true;


void player_selection(char *board, char item)

int x, y;
printf("enter coords (x, y): n");

while(1)

scanf(" %d %d", &x, &y);
bool succes = enter_entry(board, item, x-1, y-1);
if(succes)

break;

printf("This coord is already used or not valid enter new ones:n");

print_board(board);


void game_loop(char *board)

char playerOneChar = 'o';
char playerTwoChar = 'x';

printf("Welcome to tic tac toe!n");
printf("Press enter to continuen");
char enter = 0;
while (enter != 'r' && enter != 'n') enter = getchar();

printf("Let's start the game!n");
print_board(board);

while(1)

printf("Player one: n");
player_selection(board, playerOneChar);
if(is_solved(board, playerOneChar))

printf("Player one won!n");
break;


if(is_draw(board))

printf("No winners!n");
break;


printf("Player two: n");
player_selection(board, playerTwoChar);
if(is_solved(board, playerTwoChar))

printf("Player two won!");
break;

if(is_draw(board))

printf("No winners!n");
break;





Thank you in advance!










share|improve this question









New contributor



John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$


















    3












    $begingroup$


    I'm learning myself C and to make sure that I learn to code C in a proper way I created tic tac toe and want to hear your opinion on what I should do and what I shouldn't do.



    One thing is sure is to divide the code up in several files maybe but outside of that.



    The code:



    #include <stdio.h>
    #include <stdlib.h>

    #define ROWS 3
    #define BOARD_SIZE ROWS * ROWS

    typedef enum false, true bool;

    bool enter_entry(char *board, char character, int x, int y);
    void print_board(const char *board);
    void *init_board();
    bool is_solved(char *board, char item);
    bool is_draw(char *board);
    bool is_equal(char *board, int indexA, int indexB, int indexC, char item);
    void player_selection(char *board, char item);
    void game_loop(char *board);

    int main()

    char *board = init_board();
    game_loop(board);
    return 0;


    void *init_board()

    char *board = malloc(sizeof(char) * BOARD_SIZE);
    for(int i = 0; i < BOARD_SIZE; i++)

    board[i] = ' ';

    return board;


    void print_board(const char *board)

    for(int i = 1; i < BOARD_SIZE+1; i++)
    %c ", board[i-1]);
    if(i % 3 == 0)
    n");


    printf("n");


    bool is_solved(char *board, char item)

    if(is_equal(board, 0, 1, 2, item)) return true;
    if(is_equal(board, 3, 4, 5, item)) return true;
    if(is_equal(board, 6, 7, 8, item)) return true;

    if(is_equal(board, 0, 3, 6, item)) return true;
    if(is_equal(board, 1, 4, 7, item)) return true;
    if(is_equal(board, 2, 5, 8, item)) return true;

    if(is_equal(board, 0, 4, 8, item)) return true;
    if(is_equal(board, 2, 4, 6, item)) return true;
    return false;


    bool is_draw(char *board)

    for(int i = 0; i < BOARD_SIZE; i++)

    if(board[i] == ' ')

    return false;


    return true;


    bool is_equal(char *board, int indexA, int indexB, int indexC, char item)

    if(board[indexA] == item && board[indexB] == item && board[indexC] == item)

    return true;

    return false;


    bool enter_entry(char *board, char character, int x, int y)

    int index = x + ROWS * y;

    if(board[index] != ' ')

    return false;


    board[index] = character;
    return true;


    void player_selection(char *board, char item)

    int x, y;
    printf("enter coords (x, y): n");

    while(1)

    scanf(" %d %d", &x, &y);
    bool succes = enter_entry(board, item, x-1, y-1);
    if(succes)

    break;

    printf("This coord is already used or not valid enter new ones:n");

    print_board(board);


    void game_loop(char *board)

    char playerOneChar = 'o';
    char playerTwoChar = 'x';

    printf("Welcome to tic tac toe!n");
    printf("Press enter to continuen");
    char enter = 0;
    while (enter != 'r' && enter != 'n') enter = getchar();

    printf("Let's start the game!n");
    print_board(board);

    while(1)

    printf("Player one: n");
    player_selection(board, playerOneChar);
    if(is_solved(board, playerOneChar))

    printf("Player one won!n");
    break;


    if(is_draw(board))

    printf("No winners!n");
    break;


    printf("Player two: n");
    player_selection(board, playerTwoChar);
    if(is_solved(board, playerTwoChar))

    printf("Player two won!");
    break;

    if(is_draw(board))

    printf("No winners!n");
    break;





    Thank you in advance!










    share|improve this question









    New contributor



    John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    $endgroup$














      3












      3








      3





      $begingroup$


      I'm learning myself C and to make sure that I learn to code C in a proper way I created tic tac toe and want to hear your opinion on what I should do and what I shouldn't do.



      One thing is sure is to divide the code up in several files maybe but outside of that.



      The code:



      #include <stdio.h>
      #include <stdlib.h>

      #define ROWS 3
      #define BOARD_SIZE ROWS * ROWS

      typedef enum false, true bool;

      bool enter_entry(char *board, char character, int x, int y);
      void print_board(const char *board);
      void *init_board();
      bool is_solved(char *board, char item);
      bool is_draw(char *board);
      bool is_equal(char *board, int indexA, int indexB, int indexC, char item);
      void player_selection(char *board, char item);
      void game_loop(char *board);

      int main()

      char *board = init_board();
      game_loop(board);
      return 0;


      void *init_board()

      char *board = malloc(sizeof(char) * BOARD_SIZE);
      for(int i = 0; i < BOARD_SIZE; i++)

      board[i] = ' ';

      return board;


      void print_board(const char *board)

      for(int i = 1; i < BOARD_SIZE+1; i++)
      %c ", board[i-1]);
      if(i % 3 == 0)
      n");


      printf("n");


      bool is_solved(char *board, char item)

      if(is_equal(board, 0, 1, 2, item)) return true;
      if(is_equal(board, 3, 4, 5, item)) return true;
      if(is_equal(board, 6, 7, 8, item)) return true;

      if(is_equal(board, 0, 3, 6, item)) return true;
      if(is_equal(board, 1, 4, 7, item)) return true;
      if(is_equal(board, 2, 5, 8, item)) return true;

      if(is_equal(board, 0, 4, 8, item)) return true;
      if(is_equal(board, 2, 4, 6, item)) return true;
      return false;


      bool is_draw(char *board)

      for(int i = 0; i < BOARD_SIZE; i++)

      if(board[i] == ' ')

      return false;


      return true;


      bool is_equal(char *board, int indexA, int indexB, int indexC, char item)

      if(board[indexA] == item && board[indexB] == item && board[indexC] == item)

      return true;

      return false;


      bool enter_entry(char *board, char character, int x, int y)

      int index = x + ROWS * y;

      if(board[index] != ' ')

      return false;


      board[index] = character;
      return true;


      void player_selection(char *board, char item)

      int x, y;
      printf("enter coords (x, y): n");

      while(1)

      scanf(" %d %d", &x, &y);
      bool succes = enter_entry(board, item, x-1, y-1);
      if(succes)

      break;

      printf("This coord is already used or not valid enter new ones:n");

      print_board(board);


      void game_loop(char *board)

      char playerOneChar = 'o';
      char playerTwoChar = 'x';

      printf("Welcome to tic tac toe!n");
      printf("Press enter to continuen");
      char enter = 0;
      while (enter != 'r' && enter != 'n') enter = getchar();

      printf("Let's start the game!n");
      print_board(board);

      while(1)

      printf("Player one: n");
      player_selection(board, playerOneChar);
      if(is_solved(board, playerOneChar))

      printf("Player one won!n");
      break;


      if(is_draw(board))

      printf("No winners!n");
      break;


      printf("Player two: n");
      player_selection(board, playerTwoChar);
      if(is_solved(board, playerTwoChar))

      printf("Player two won!");
      break;

      if(is_draw(board))

      printf("No winners!n");
      break;





      Thank you in advance!










      share|improve this question









      New contributor



      John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$




      I'm learning myself C and to make sure that I learn to code C in a proper way I created tic tac toe and want to hear your opinion on what I should do and what I shouldn't do.



      One thing is sure is to divide the code up in several files maybe but outside of that.



      The code:



      #include <stdio.h>
      #include <stdlib.h>

      #define ROWS 3
      #define BOARD_SIZE ROWS * ROWS

      typedef enum false, true bool;

      bool enter_entry(char *board, char character, int x, int y);
      void print_board(const char *board);
      void *init_board();
      bool is_solved(char *board, char item);
      bool is_draw(char *board);
      bool is_equal(char *board, int indexA, int indexB, int indexC, char item);
      void player_selection(char *board, char item);
      void game_loop(char *board);

      int main()

      char *board = init_board();
      game_loop(board);
      return 0;


      void *init_board()

      char *board = malloc(sizeof(char) * BOARD_SIZE);
      for(int i = 0; i < BOARD_SIZE; i++)

      board[i] = ' ';

      return board;


      void print_board(const char *board)

      for(int i = 1; i < BOARD_SIZE+1; i++)
      %c ", board[i-1]);
      if(i % 3 == 0)
      n");


      printf("n");


      bool is_solved(char *board, char item)

      if(is_equal(board, 0, 1, 2, item)) return true;
      if(is_equal(board, 3, 4, 5, item)) return true;
      if(is_equal(board, 6, 7, 8, item)) return true;

      if(is_equal(board, 0, 3, 6, item)) return true;
      if(is_equal(board, 1, 4, 7, item)) return true;
      if(is_equal(board, 2, 5, 8, item)) return true;

      if(is_equal(board, 0, 4, 8, item)) return true;
      if(is_equal(board, 2, 4, 6, item)) return true;
      return false;


      bool is_draw(char *board)

      for(int i = 0; i < BOARD_SIZE; i++)

      if(board[i] == ' ')

      return false;


      return true;


      bool is_equal(char *board, int indexA, int indexB, int indexC, char item)

      if(board[indexA] == item && board[indexB] == item && board[indexC] == item)

      return true;

      return false;


      bool enter_entry(char *board, char character, int x, int y)

      int index = x + ROWS * y;

      if(board[index] != ' ')

      return false;


      board[index] = character;
      return true;


      void player_selection(char *board, char item)

      int x, y;
      printf("enter coords (x, y): n");

      while(1)

      scanf(" %d %d", &x, &y);
      bool succes = enter_entry(board, item, x-1, y-1);
      if(succes)

      break;

      printf("This coord is already used or not valid enter new ones:n");

      print_board(board);


      void game_loop(char *board)

      char playerOneChar = 'o';
      char playerTwoChar = 'x';

      printf("Welcome to tic tac toe!n");
      printf("Press enter to continuen");
      char enter = 0;
      while (enter != 'r' && enter != 'n') enter = getchar();

      printf("Let's start the game!n");
      print_board(board);

      while(1)

      printf("Player one: n");
      player_selection(board, playerOneChar);
      if(is_solved(board, playerOneChar))

      printf("Player one won!n");
      break;


      if(is_draw(board))

      printf("No winners!n");
      break;


      printf("Player two: n");
      player_selection(board, playerTwoChar);
      if(is_solved(board, playerTwoChar))

      printf("Player two won!");
      break;

      if(is_draw(board))

      printf("No winners!n");
      break;





      Thank you in advance!







      beginner c tic-tac-toe






      share|improve this question









      New contributor



      John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share|improve this question









      New contributor



      John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share|improve this question




      share|improve this question








      edited 10 hours ago









      dfhwze

      2,100322




      2,100322






      New contributor



      John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      asked 10 hours ago









      JohnJohn

      1184




      1184




      New contributor



      John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




      New contributor




      John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          1 Answer
          1






          active

          oldest

          votes


















          3












          $begingroup$

          malloc



          I start with one of the most common ones. Instead of char *board = malloc(sizeof(char) * BOARD_SIZE) write char *board = malloc(sizeof(*board) * BOARD_SIZE). If you decide to change the type in the future, you don't have to change at more than one place. And besides, sizeof(char) is ALWAYS 1.



          But the biggest problem is that you're not checking the return value. It should look like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(!board)
          /* Handle error */
          else
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          Or like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(board)
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          But if you choose the latter one, then you need to check the return value of init_board().



          Another thing about the board variable. Why not make it into a 3x3 array instead? It's overkill to call malloc for a 9 byte array. I would do like this instead:



          const int dim=3;

          void init_board(char board[dim][dim])

          for(int i=0; i<dim; i++)
          for(int j=0; j<dim, j++)
          board[i][j]=' ';



          And then in main()



          char board[3][3];
          init_board(board);


          scanf



          You're also not checking the return value of scanf. That should also always be done.



          scanf(" %d %d", &x, &y);


          should be



          if(scanf(" %d %d", &x, &y) != 2) 
          /* Handle error */
          else {


          But if you ask me, the best method, even though it takes a few more lines, is this:



          const size_t buffer_size = 100;
          char buffer[buffer_size];
          if(!fgets(buffer, buffer_size, stdin))
          /* Handle error */
          else
          if(sscanf(buffer, "%d %d", &x, &y) != 2)
          /* Handle error */




          bool



          No reason to define bool, true and false on your own. Just include stdbool.h.



          const



          A minor thing is that you should declare playerOneChar and playerTwoChar as const.



          style



          This is my personal preference, but I think you waste a lot of space with unnecessary braces. I would at least move the opening brace to then end of previous line, except for functions. Like this:



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;


          return true;



          or even



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;
          return true;



          Remember that readability also includes not having to scroll more than necessary. Putting the opening brace on the line before or sometimes even removing them completely barely makes it harder to read at all. If you ask me it's even easier. But it can save you a ton of lines, making more code visible at the same time. In the above example I would probably remove the braces for the if statement, but keep the braces for the for loop.



          Apart from these things, I think it looks pretty good. Nice work.






          share|improve this answer











          $endgroup$












          • $begingroup$
            Thanks Broman for your comments, I will take them into account! Thanks!
            $endgroup$
            – John
            9 hours ago











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          John is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221943%2ftictactoe-classic-in-c%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3












          $begingroup$

          malloc



          I start with one of the most common ones. Instead of char *board = malloc(sizeof(char) * BOARD_SIZE) write char *board = malloc(sizeof(*board) * BOARD_SIZE). If you decide to change the type in the future, you don't have to change at more than one place. And besides, sizeof(char) is ALWAYS 1.



          But the biggest problem is that you're not checking the return value. It should look like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(!board)
          /* Handle error */
          else
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          Or like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(board)
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          But if you choose the latter one, then you need to check the return value of init_board().



          Another thing about the board variable. Why not make it into a 3x3 array instead? It's overkill to call malloc for a 9 byte array. I would do like this instead:



          const int dim=3;

          void init_board(char board[dim][dim])

          for(int i=0; i<dim; i++)
          for(int j=0; j<dim, j++)
          board[i][j]=' ';



          And then in main()



          char board[3][3];
          init_board(board);


          scanf



          You're also not checking the return value of scanf. That should also always be done.



          scanf(" %d %d", &x, &y);


          should be



          if(scanf(" %d %d", &x, &y) != 2) 
          /* Handle error */
          else {


          But if you ask me, the best method, even though it takes a few more lines, is this:



          const size_t buffer_size = 100;
          char buffer[buffer_size];
          if(!fgets(buffer, buffer_size, stdin))
          /* Handle error */
          else
          if(sscanf(buffer, "%d %d", &x, &y) != 2)
          /* Handle error */




          bool



          No reason to define bool, true and false on your own. Just include stdbool.h.



          const



          A minor thing is that you should declare playerOneChar and playerTwoChar as const.



          style



          This is my personal preference, but I think you waste a lot of space with unnecessary braces. I would at least move the opening brace to then end of previous line, except for functions. Like this:



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;


          return true;



          or even



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;
          return true;



          Remember that readability also includes not having to scroll more than necessary. Putting the opening brace on the line before or sometimes even removing them completely barely makes it harder to read at all. If you ask me it's even easier. But it can save you a ton of lines, making more code visible at the same time. In the above example I would probably remove the braces for the if statement, but keep the braces for the for loop.



          Apart from these things, I think it looks pretty good. Nice work.






          share|improve this answer











          $endgroup$












          • $begingroup$
            Thanks Broman for your comments, I will take them into account! Thanks!
            $endgroup$
            – John
            9 hours ago















          3












          $begingroup$

          malloc



          I start with one of the most common ones. Instead of char *board = malloc(sizeof(char) * BOARD_SIZE) write char *board = malloc(sizeof(*board) * BOARD_SIZE). If you decide to change the type in the future, you don't have to change at more than one place. And besides, sizeof(char) is ALWAYS 1.



          But the biggest problem is that you're not checking the return value. It should look like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(!board)
          /* Handle error */
          else
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          Or like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(board)
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          But if you choose the latter one, then you need to check the return value of init_board().



          Another thing about the board variable. Why not make it into a 3x3 array instead? It's overkill to call malloc for a 9 byte array. I would do like this instead:



          const int dim=3;

          void init_board(char board[dim][dim])

          for(int i=0; i<dim; i++)
          for(int j=0; j<dim, j++)
          board[i][j]=' ';



          And then in main()



          char board[3][3];
          init_board(board);


          scanf



          You're also not checking the return value of scanf. That should also always be done.



          scanf(" %d %d", &x, &y);


          should be



          if(scanf(" %d %d", &x, &y) != 2) 
          /* Handle error */
          else {


          But if you ask me, the best method, even though it takes a few more lines, is this:



          const size_t buffer_size = 100;
          char buffer[buffer_size];
          if(!fgets(buffer, buffer_size, stdin))
          /* Handle error */
          else
          if(sscanf(buffer, "%d %d", &x, &y) != 2)
          /* Handle error */




          bool



          No reason to define bool, true and false on your own. Just include stdbool.h.



          const



          A minor thing is that you should declare playerOneChar and playerTwoChar as const.



          style



          This is my personal preference, but I think you waste a lot of space with unnecessary braces. I would at least move the opening brace to then end of previous line, except for functions. Like this:



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;


          return true;



          or even



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;
          return true;



          Remember that readability also includes not having to scroll more than necessary. Putting the opening brace on the line before or sometimes even removing them completely barely makes it harder to read at all. If you ask me it's even easier. But it can save you a ton of lines, making more code visible at the same time. In the above example I would probably remove the braces for the if statement, but keep the braces for the for loop.



          Apart from these things, I think it looks pretty good. Nice work.






          share|improve this answer











          $endgroup$












          • $begingroup$
            Thanks Broman for your comments, I will take them into account! Thanks!
            $endgroup$
            – John
            9 hours ago













          3












          3








          3





          $begingroup$

          malloc



          I start with one of the most common ones. Instead of char *board = malloc(sizeof(char) * BOARD_SIZE) write char *board = malloc(sizeof(*board) * BOARD_SIZE). If you decide to change the type in the future, you don't have to change at more than one place. And besides, sizeof(char) is ALWAYS 1.



          But the biggest problem is that you're not checking the return value. It should look like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(!board)
          /* Handle error */
          else
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          Or like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(board)
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          But if you choose the latter one, then you need to check the return value of init_board().



          Another thing about the board variable. Why not make it into a 3x3 array instead? It's overkill to call malloc for a 9 byte array. I would do like this instead:



          const int dim=3;

          void init_board(char board[dim][dim])

          for(int i=0; i<dim; i++)
          for(int j=0; j<dim, j++)
          board[i][j]=' ';



          And then in main()



          char board[3][3];
          init_board(board);


          scanf



          You're also not checking the return value of scanf. That should also always be done.



          scanf(" %d %d", &x, &y);


          should be



          if(scanf(" %d %d", &x, &y) != 2) 
          /* Handle error */
          else {


          But if you ask me, the best method, even though it takes a few more lines, is this:



          const size_t buffer_size = 100;
          char buffer[buffer_size];
          if(!fgets(buffer, buffer_size, stdin))
          /* Handle error */
          else
          if(sscanf(buffer, "%d %d", &x, &y) != 2)
          /* Handle error */




          bool



          No reason to define bool, true and false on your own. Just include stdbool.h.



          const



          A minor thing is that you should declare playerOneChar and playerTwoChar as const.



          style



          This is my personal preference, but I think you waste a lot of space with unnecessary braces. I would at least move the opening brace to then end of previous line, except for functions. Like this:



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;


          return true;



          or even



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;
          return true;



          Remember that readability also includes not having to scroll more than necessary. Putting the opening brace on the line before or sometimes even removing them completely barely makes it harder to read at all. If you ask me it's even easier. But it can save you a ton of lines, making more code visible at the same time. In the above example I would probably remove the braces for the if statement, but keep the braces for the for loop.



          Apart from these things, I think it looks pretty good. Nice work.






          share|improve this answer











          $endgroup$



          malloc



          I start with one of the most common ones. Instead of char *board = malloc(sizeof(char) * BOARD_SIZE) write char *board = malloc(sizeof(*board) * BOARD_SIZE). If you decide to change the type in the future, you don't have to change at more than one place. And besides, sizeof(char) is ALWAYS 1.



          But the biggest problem is that you're not checking the return value. It should look like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(!board)
          /* Handle error */
          else
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          Or like this:



          void *init_board()

          char *board = malloc(sizeof(char) * BOARD_SIZE);
          if(board)
          for(int i = 0; i < BOARD_SIZE; i++)
          board[i] = ' ';


          return board;



          But if you choose the latter one, then you need to check the return value of init_board().



          Another thing about the board variable. Why not make it into a 3x3 array instead? It's overkill to call malloc for a 9 byte array. I would do like this instead:



          const int dim=3;

          void init_board(char board[dim][dim])

          for(int i=0; i<dim; i++)
          for(int j=0; j<dim, j++)
          board[i][j]=' ';



          And then in main()



          char board[3][3];
          init_board(board);


          scanf



          You're also not checking the return value of scanf. That should also always be done.



          scanf(" %d %d", &x, &y);


          should be



          if(scanf(" %d %d", &x, &y) != 2) 
          /* Handle error */
          else {


          But if you ask me, the best method, even though it takes a few more lines, is this:



          const size_t buffer_size = 100;
          char buffer[buffer_size];
          if(!fgets(buffer, buffer_size, stdin))
          /* Handle error */
          else
          if(sscanf(buffer, "%d %d", &x, &y) != 2)
          /* Handle error */




          bool



          No reason to define bool, true and false on your own. Just include stdbool.h.



          const



          A minor thing is that you should declare playerOneChar and playerTwoChar as const.



          style



          This is my personal preference, but I think you waste a lot of space with unnecessary braces. I would at least move the opening brace to then end of previous line, except for functions. Like this:



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;


          return true;



          or even



          bool is_draw(char *board)

          for(int i = 0; i < BOARD_SIZE; i++)
          if(board[i] == ' ')
          return false;
          return true;



          Remember that readability also includes not having to scroll more than necessary. Putting the opening brace on the line before or sometimes even removing them completely barely makes it harder to read at all. If you ask me it's even easier. But it can save you a ton of lines, making more code visible at the same time. In the above example I would probably remove the braces for the if statement, but keep the braces for the for loop.



          Apart from these things, I think it looks pretty good. Nice work.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 9 hours ago

























          answered 10 hours ago









          BromanBroman

          574211




          574211











          • $begingroup$
            Thanks Broman for your comments, I will take them into account! Thanks!
            $endgroup$
            – John
            9 hours ago
















          • $begingroup$
            Thanks Broman for your comments, I will take them into account! Thanks!
            $endgroup$
            – John
            9 hours ago















          $begingroup$
          Thanks Broman for your comments, I will take them into account! Thanks!
          $endgroup$
          – John
          9 hours ago




          $begingroup$
          Thanks Broman for your comments, I will take them into account! Thanks!
          $endgroup$
          – John
          9 hours ago










          John is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          John is a new contributor. Be nice, and check out our Code of Conduct.












          John is a new contributor. Be nice, and check out our Code of Conduct.











          John is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221943%2ftictactoe-classic-in-c%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

          Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

          199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單