The program is a Tic-Tac-Toe game, and it hangs after taking the X and Y values from the user.
This is the main file:
#include <stdio.h>
#include <string.h>
#include "input.cpp"
int makeMove(char** board, char* moveX, char* moveY, char playerMove) {
printf("Make your x move: ");
int answerX = (int)getNum(moveX, 2);
printf("Make your y move: ");
int answerY = (int)getNum(moveY, 2);
answerX--;
answerY--;
if ((answerX < 0) || (answerX > 2)) {
return -1;
}
if ((answerY < 0) || (answerY > 2)) {
return -1;
}
board[answerY][answerX] = playerMove;
return 0;
}
int main()
{
int turns = 0;
const int MAX_TURNS = 9;
char playerOneChar = 'X';
char playerTwoChar = 'O';
char currentChar = playerOneChar;
while (turns <= MAX_TURNS) {
char board[3][3];
memset(board, ' ', 9);
char moveX[2];
memset(moveX, ' ', 2);
char moveY[2];
memset(moveY, ' ', 2);
int result = makeMove(board, moveX, moveY, currentChar);
if (result == 0) {
if (currentChar == playerOneChar) {
currentChar = playerTwoChar;
}
else {
currentChar = playerOneChar;
}
turns++;
}
else {
printf("Player move was out of bounds.");
}
}
}
This is input.cpp, and it is designed to safely get a number from the user, without allowing for buffer overruns or other problems:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
long getNum(char* buffer, int bufferSize)
{
long answer;
int success = 0;
while (!success)
{
// This gets the input from the user
if (!fgets(buffer, bufferSize, stdin))
{
//If fgets fails, return with exit code 1.
return 1;
}
char* endptr;
errno = 0;
answer = strtol(buffer, &endptr, 10);
// If an error occurs, the user is told the number is too small or large.
if (errno == ERANGE)
{
printf("Sorry, this number is too small or too large.\n");
success = 0;
}
else if (endptr == buffer)
{
success = 0;
}
else if (*endptr && *endptr != '\n')
{
success = 0;
}
else
{
success = 1;
}
}
return answer;
}
I attempted to input 2 numbers, but the program hanged afterwards. I attempted to research on the internet, but there was a lack of any explanation for why a function was not able to write to a 2D array properly. I am assuming that it hangs because char** is a pointer to char*, rather than being a pointer to a 2D array of chars.