christian christian - 4 months ago 27
C Question

C Tick tac toe beginner

Im getting an segmentation fault error any suggestions? Im trying to create a tic tack toe game, just started programming in c. Any suggestions would be helpful. I just want it to print to the terminal no graphics for now.

#include <stdio.h>

int main()
{
int Board[9];
char row1[3];
char row2[3];
char row3[3];
int j = 0;
int turns = 0;
char x;
x = 'x';
char o;
o='o';
int spot;
printf("Hello, and welcome to christians Tick Tack Toe game\n");
printf("Heres how it works: X goes first and chooses a place(1-9 corresponding to a place on the board)\n");
printf("First to get 3 in a row wins. Have fun!\n");
printf("X goes first where do you want to go?");
scanf("%d", &spot);
Board[spot-1] = 1;
turns = 1;
if (spot <=3)
{

row1[spot-1] = x;
for (j =0; j<3; j++)
{
printf("%c", row1[j]);

}
for (j =0; j<3; j++)
{
printf("%c", row2[j]);

}
for (j=0; j<3; j++)
{
printf("%c", row3[j]);

}
}
else if(spot >3 && spot <=6)
{

row2[spot - 4] = x;
for (j =0; j<3; j++)
{
printf("%c", row1[j]);

}
for (j =0; j<3; j++)
{
printf("%c", row2[j]);

}
for (j=0; j<3; j++)
{
printf("%c", row3[j]);

}
}
else
{
row3[spot - 7] = x;
for (j =0; j<3; j++)
{
printf("\n%c", row1[j]);

}
for (j =0; j<3; j++)
{
printf("%c", row2[j]);

}
for (j=0; j<3; j++)
{
printf("%c", row3[j]);

}
}

}

Answer
  • You invoked undefined behavior by passing data having wrong type to printf(). The format specifier to print one character is %c, not %s.
  • Your usage of for statement is wrong, so j will be too big and undefined behavior will be invoked by accessing out-of-range of an array.

Example of wrong code:

for (j<3; j++;)
{
    printf("%s", row1[j]);
}

Corrected code:

for (j=0; j<3; j++)
{
    printf("%c", row1[j]);
}

The same correction is required for loops using row2 and row3.


More mistakes:

  • scanf("%s", &spot); will invoke undefined behavior: wrong specifier is used again. %d should be used to read integers.
  • char x ="x"; and char o = "o"; are bad because the values converted from the pointers converted from the string literals should be meaningless. You should use character constants instead like char x ='x'; and char o = 'o';.
  • Array indexes in C will begin with 0, not 1. row1[3] is not a valid object and you mustn't write something there when it is declared as char row1[3];. You should correct like
    • row1[spot] = x; -> row1[spot - 1] = x;
    • row2[spot - 3] = x; -> row2[spot - 4] = x;
    • row3[spot - 6] = x; -> row3[spot - 7] = x;
  • Using values of uninitialized variables having automatic storage duration, which is indeterminate, invokes undefined behavior. You have to initialized variables before using their values like char row1[3] = " ";. Also initialize row2 and row3 like this.
Comments