Receiving exit code -1073741819 when program is ran - c

I'm making a tic-tac-toe program in C. My code is listed below.
#include <stdio.h>
#include <conio.h>
char evaluateWinConditions(char board[3][3]);
int main(void)
{
puts("---");
puts("---");
puts("---");
char board[3][3] = {{"-"}}; // board
char key = 0; // stores key presses
// stores position of mouse pointer
int row = 1;
int column = 1;
// stores player turn
int player = 1;
printf("\033[%d;%dH", row, column);
while (evaluateWinConditions(board) == 0) {
key = _getch();
switch (key) {
case 'a':
column -= 1;
break;
case 'w':
row -= 1;
break;
case 'd':
column += 1;
break;
case 's':
row += 1;
break;
case ' ':
if (player == 1) {
printf("%c", 'X');
board[row][column] = 'X';
player = 2;
}
else {
printf("%c", 'O');
board[row][column] == 'O';
player = 1;
}
break;
}
printf("\033[%d;%dH", row, column);
}
printf("\033[5;1H");
if (evaluateWinConditions(board == 1)) printf("Player 1 wins.");
else printf("Player 2 wins.");
}
char evaluateWinConditions(char board[3][3])
{
if (board[0][0] == board[0][1] == board[0][2] ||
board[1][0] == board[1][1] == board[1][2] ||
board[2][0] == board[2][1] == board[2][2] ||
board[0][0] == board[1][1] == board[2][2] ||
board[0][2] == board[1][1] == board[2][0]) {
if (board[0][0] == "X") return 1;
else return 2;
}
else {
return 0;
}
}
When I compile the program, there's no errors. However, I receive a run time error with code -1073741819 when I run the program. I'm using Windows 10 64-bit and Visual Studio 2019. This error appears after about one second when I run the program. When I debug the program in Visual Studio, I receive an error on line 74 "Exception thrown: read access violation; board was nullptr"

The probable cause of the exception is a consequence of the nonsensical comparison board == 1 in the function call evaluateWinConditions(board == 1). The board == 1 comparison is a constraint violation (use of equality operator between pointer and integer that isn't a null pointer constant) that is probably evaluating to the int value 0, and that int value 0 (which is not a null pointer constant here) is probably being converted in an implementation-defined way to a null pointer (which is another constraint violation due to lack of an explicit cast) of type char (*)[3] to become the value of the board parameter in the evaluateWinConditions function. The evaluateWinConditions function is dereferencing that null pointer, resulting in an access violation exception.
There are plenty of other errors in the original code.

Related

Creating Tic-Tac-Toe in C - array not showing changes, not returning error messages

I am trying to create a tic-tac-toe game in C.
My instructions are as follows:
Write a C program that lets two people play tic-tac-toe. Use a global array: char ttt[3][3]; to represent the board state, and globals for the player (a char to hold X or O or whatever you characters you want), i and j integers for indexes, and an integer to count the number of moves completed. Show the game board for each move two characters for the players with a key for the user to type one character or digit to say what spot to take in the board. At the end of a game, say who won or that it is a tie. Have at least the functions to print the board, get a valid move, and check for a win; do use printf, scanf, if-else, switch (to find indexes into ttt) while, for.
My code is as follows:
#include <stdio.h>
#include <conio.h>
// Global array for the board
char ttt[3][3] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'}
};
void PrintTheBoard() { // Print the board as it currently is
printf("| %c | | %c | | %c |\n", ttt[0][0], ttt[0][1], ttt[0][2]);
printf("| %c | | %c | | %c |\n", ttt[1][0], ttt[1][1], ttt[1][2]);
printf("| %c | | %c | | %c |\n", ttt[2][0], ttt[2][1], ttt[2][2]);
}
// Check for a win
int CheckForWin() {
// Checks for horizontal win conditions
if (ttt[0][0] == ttt[0][1] && ttt[0][1] == ttt[0][2])
return 1;
else if (ttt[1][0] == ttt[1][1] && ttt[1][1] == ttt[1][2])
return 1;
else if (ttt[2][0] == ttt[2][1] && ttt[2][1] == ttt[2][2])
return 1;
// Checks for vertical wins
else if (ttt[0][0] == ttt[1][0] && ttt[1][0] == ttt[2][0])
return 1;
else if (ttt[0][1] == ttt[1][1] && ttt[1][1] == ttt[2][1])
return 1;
else if (ttt[0][2] == ttt[1][2] && ttt[1][2] == ttt[2][2])
return 1;
// Checks for diagonal wins
else if (ttt[0][0] == ttt[1][1] && ttt[1][1] == ttt[2][2])
return 1;
else if (ttt[0][2] == ttt[1][1] && ttt[1][1] == ttt[2][0])
return 1;
else if (ttt[0][0] != '1' && ttt[0][1] != '2' && ttt[0][2] != '3' &&
ttt[1][0] != '4' && ttt[1][1] != '5' && ttt[1][2] != '6' &&
ttt[2][0] != '7' && ttt[2][1] != '8' && ttt[2][2] != '9')
return 2;
else
return 0;
}
int main() { // The function below gets a move, validates it, and keep tracks of the # of moves made.
int choice;
int player = 1;
int i;
int counter = 0;
char mark;
int isValid;
// Gets user input
do {
PrintTheBoard();
player = (player % 2) ? 1 : 2;
printf("Player %d, enter a number: ", player);
scanf("%d", &choice);
// Determines what mark to make, depending on the current player by way of "if current player is player 1, use X, otherwise, use O"
mark = (player == 1) ? 'X' : 'O';
/*
The below switch function is a bit convoluted. Depending on the value of the "choice" variable (1-9, chosen by the active player
and corresponding to a position on the board), the value is checked for position validity by checking if the position in the
array corresponding to the choice still has its original numeral value, which indicates the spot is not taken.
If it still has that original value, the position is assigned an X or an O depending on the current player.
If the spot is taken, indicated by the value not being equal to its original numeral, the player is told that the position is
invalid.
If the player does not choose a valid case, the player is informed of this and told what to do.
*/
switch(choice) {
case 1:
if (ttt[0][0] == '1') {
ttt[0][0] = mark;
}
break;
case 2:
if (ttt[0][1] == '2') {
ttt[0][1] = mark;
}
break;
case 3:
if (ttt[0][2] == '3') {
ttt[0][2] = mark;
}
break;
case 4:
if (ttt[1][0] == '4') {
ttt[1][0] = mark;
}
break;
case 5:
if (ttt[1][1] == '5') {
ttt[1][1] = mark;
}
break;
case 6:
if (ttt[1][2] == '6') {
ttt[1][2] = mark;
}
break;
case 7:
if (ttt[2][0] == '7') {
ttt[2][0] = mark;
}
break;
case 8:
if (ttt[2][1] == '8') {
ttt[2][1] = mark;
}
break;
case 9:
if (ttt[2][2] == '9') {
ttt[2][2] = mark;
}
break;
default:
printf("Invalid input. Please choose and type a number 1-9 corresponding to a position that is not already taken.\n");
printf("Press any key to continue.\n");
player--;
getch();
}
i = CheckForWin();
if (i != 1 && i != 2)
player++;
} while (i == 0);
PrintTheBoard();
if (i == 1)
printf("Player %d wins!", player);
else
printf("The game is a draw!");
}
My issue is that the error message is not printed when the two players choose the same spot. The program then goes to the next players turn, effectively skipping the player who chose an occupied spot. The player who occupied the spot in question keeps the spot.
Furthermore, I don't really understand how to use i and j integers to fill out the indexes. When I try code blocks previously used for this, tons of errors show up.
Thanks for any help.
Try adding an extra boolean variable and moving the error message outside of the switch:
int okay = 0;
switch (choice) {
case 1:
if (ttt[0][0] == '1') {
ttt[0][0] = mark;
okay = 1;
}
break;
case 2:
if (ttt[0][1] == '2') {
ttt[0][1] = mark;
okay = 1;
}
break;
case 3:
if (ttt[0][2] == '3') {
ttt[0][2] = mark;
okay = 1;
}
break;
case 4:
if (ttt[1][0] == '4') {
ttt[1][0] = mark;
okay = 1;
}
break;
case 5:
if (ttt[1][1] == '5') {
ttt[1][1] = mark;
okay = 1;
}
break;
case 6:
if (ttt[1][2] == '6') {
ttt[1][2] = mark;
okay = 1;
}
break;
case 7:
if (ttt[2][0] == '7') {
ttt[2][0] = mark;
okay = 1;
}
break;
case 8:
if (ttt[2][1] == '8') {
ttt[2][1] = mark;
okay = 1;
}
break;
case 9:
if (ttt[2][2] == '9') {
ttt[2][2] = mark;
okay = 1;
}
break;
}
if (! okay) {
printf("Invalid input. Please choose and type a number 1-9 corresponding to a position that is not already taken.\n");
printf("Press any key to continue.\n");
player--;
getch();
}
With a bit of trickery, we can make this a bit more compact:
int savemark = mark;
switch (choice) {
case 1:
if (ttt[0][0] == '1') {
ttt[0][0] = mark++;
}
break;
case 2:
if (ttt[0][1] == '2') {
ttt[0][1] = mark++;
}
break;
case 3:
if (ttt[0][2] == '3') {
ttt[0][2] = mark++;
}
break;
case 4:
if (ttt[1][0] == '4') {
ttt[1][0] = mark++;
}
break;
case 5:
if (ttt[1][1] == '5') {
ttt[1][1] = mark++;
}
break;
case 6:
if (ttt[1][2] == '6') {
ttt[1][2] = mark++;
}
break;
case 7:
if (ttt[2][0] == '7') {
ttt[2][0] = mark++;
}
break;
case 8:
if (ttt[2][1] == '8') {
ttt[2][1] = mark++;
}
break;
case 9:
if (ttt[2][2] == '9') {
ttt[2][2] = mark++;
}
break;
}
if (mark == savemark) {
printf("Invalid input. Please choose and type a number 1-9 corresponding to a position that is not already taken.\n");
printf("Press any key to continue.\n");
player--;
getch();
}
You mentioned that you must use a switch but expressed the desire to see the more compact solution. So, here's a way:
int okay = 0;
do {
if (choice < 1)
break;
if (choice > 9)
break;
choice -= 1;
if (ttt[choice / 3][choice % 3] == ('1' + choice)) {
ttt[choice / 3][choice % 3] = mark;
okay = 1;
}
} while (0);
if (! okay) {
printf("Invalid input. Please choose and type a number 1-9 corresponding to a position that is not already taken.\n");
printf("Press any key to continue.\n");
player--;
getch();
}

fixing an error i cannot spot in main() in C (stuck for hours on it - short program)

i'm having real hard time with my code, and my due date is today. i'm given an error "main.c: In function ‘main’:
main.c:186:7: error: expected declaration or statement at end of input
}".
I've been trying for hours to play with the brackets and fix it but with no luck. i'm hoping you could help me fix it, as you are far more experienced than me.
it's basically a simple program that takes input from stdin(might be from keyboard or from a file using redirection) and applies the following:
1)puts a new line between sentences.
2)doesn't print numbers.
3)if inside a bracket, then letters must be capitalized(bold).
4)put's an uppercase on a first character of a sentence.
5)if not in a bracket nor in a beginning of a sentence, then it should make it a lowercase.
notes:
a)there's no limit on the length of the input, and each sentence can be written on several lines(the input).
b)if a dot (.) is inside a brackets, it doesn't make it a new sentence(no need to write a newline).
c)if two dots are given, then it's an empty sentence and should be written like the example.
basically, i just ask you to help me fix my code so it will run, as i've already done all of that(thought of i missed something and you can help me improve it - i will be very glad!)
example:
if given input:
i love to play hockey.. I NEED TO PLAY HOCKEY.. "hockey is life 3333".
the desired output will be:
I love to play hockey.
. I need to play hockey.
.
"HOCKEY IS LIFE"
the code in "temp.h" is:
#define go 0
#define endOfASentence 1
#define isAFirstQuotation 2
#define isASecondQuotation 3
#define inAQuotation 4
#define beginningOfSentence 5
#define middleOfSentence 6
the code in main program is:
#include <stdio.h>
#include <ctype.h>
#include "letters.h"
int checkIfLetter (char a); /*checking if char is a letter */
int checkIfnumber (char a); /*checking if char is a number */
int checkIfUpperCase (char a); /*checking if char is upper case */
int checkIfLowerCase (char a); /*checking if char is lower case */
int checkIfQuotation (char a); /*check if char is a quotation */
int checkIfDot (char a); /*check if char is a dot */
int
main (int argc, const char *argv[])
{
int status = go;
char a;
int beginning = 0; /*if beginning equals 0 it's the beginning of a sentence, if it's 1 then it's the middle of it */
int secondQuote = 0; /*if second quote equals 1, then it's inside of a quotation */
while ((a = getchar ()) != EOF)
{
switch (status)
{
case go:
if (a == '.')
{
status = endOfASentence;
}
else if (a == '"' && secondQuote == '0')
{
status = isAFirstQuotation;
}
else if (a == '"' && secondQuote == '1')
{
status = isASecondQuotation;
}
else if (checkIfLetter (a) == '1' && secondQuote == '1')
{
status = inAQuotation;
}
else if (checkIfnumber (a) == '1')
{
continue;
} /*a number should not be on the output, so we just ignore it and not using it */
else if (checkIfLetter (a) == '1' && beginning == '0')
{
status = beginningOfSentence;
} /*i tried to differentiate between beginning and middle of the sentence using int beginning */
else if (checkIfLetter (a) == '1' && beginning == '1')
{
status = middleOfSentence;
}
case beginningOfSentence:
if (checkIfQuotation (a) && checkIfDot (a)
&& checkIfnumber (a) != 1)
{
if (checkIfUpperCase (a) == '1')
{
printf ("%c", toupper (a));
beginning = 1;
status = go;
}
} break; /*set to upper and return to go */
case middleOfSentence:
if (checkIfQuotation (a) && checkIfDot (a)
&& checkIfnumber (a) != 1)
{
if (checkIfLowerCase (a) == '1')
{
printf ("%c", tolower (a));
status = go;
}
} break;
case endOfASentence:
if (checkIfDot (a) == '1')
{
printf ("%c/n", a);
beginning = 0;
status = go;
}break; /*i tried to append(add) a new line after the dot and to set beginning to 0, to signify that after it's a beginning of a sentence */
case isAFirstQuotation: /*if it's a quotation, continue to the next char and make it upper case as long as it's a lower case, until you get another quotation */
while (checkIfLowerCase (a) == '1')
{
secondQuote == '1';
status = go;
}break;
case isASecondQuotation:
if (checkIfQuotation (a) == '1' && secondQuote == '1')
{
secondQuote = 0;
status = go;
}break;
case inAQuotation:
if (secondQuote == '1' && checkIfLetter (a) == '1')
{
printf ("%c", toupper (a));
status = go;
} break;
}
}
return 0;
}
int checkIfLetter (char a)
{
if (isalpha (a))
{
return 1;
}
else
{
return 0;
}
}
int checkIfnumber (char a)
{
if (isdigit (a))
{
return 1;
}
else
{
return 0;
}
}
int checkIfUpperCase (char a)
{
if (checkIfLetter (a) == '1')
{
if (isupper (a))
{
return 1;
}
else
{
return 0;
}
}
}
int checkIfLowerCase (char a)
{
if (checkIfLetter (a) == '1')
{
if (islower (a))
{
return 1;
}
else
{
return 0;
}
}
}
int checkIfQuotation (char a)
{
if (a == '"')
{
return 1;
}
else
{
return 0;
}
}
int checkIfDot (char a)
{
if (a == '.')
{
return 1;
}
else
{
return 0;
}
}
i don't know how to fix it and i've spent hours on it. would be very grateful if you could help.
i've tried to be very elaborative and to abide the rules
You can try this to see if it produces the desired results.
Characters that are not letters, space, newline or dot are rejected at the top of the while and all letters are set to lower case.
Then the choice is to print one upper case letter at the start of the sentence or all upper case inside double quotes.
There are no breaks as oneUpper needs to fall through to allUpper. allUpper needs to fall through to default.
getchar returns an int so int a instead of char a
#include <stdio.h>
#include <ctype.h>
#define oneUpper 1
#define allUpper 2
int main (int argc, const char *argv[])
{
int status = oneUpper;
int a;
while ( EOF != (a = getchar ()))
{
//discard non letter except space, newline and .
if ( !isalpha ( a) && a != ' ' && a != '\"' && a != '.') {
continue;
}
//set all to lower and let oneUpper or allUpper do the rest.
a = tolower ( a);
switch (status)
{
case oneUpper:
if ( a == ' ' || a == '\n') {
putchar ( a);//print leading space and continue
continue;
}
case allUpper:
a = toupper ( a);
default:
putchar ( a);
if ( a == '\"') {
if ( status == allUpper) {
status = 0;//turn all upper off
}
else {
status = allUpper;//turn all upper on
}
}
if ( status == oneUpper) {
status = 0;//after printing one upper turn it off
}
if ( a == '.') {
if ( status != allUpper) {
putchar ( '\n');
status = oneUpper;//after a . turn one upper on
}
}
}
}
return 0;
}

Brainfuck interpreter in c printing trouble

I'm trying to code a very simple brainfuck interpreter in C, and I run into problems while trying to outprint certain characters by what I understand.
This is all my code:
#include <stdio.h>
int bla(char tabukaz[30000], int ukaz, int num) {
int sum = 0;
int index = ukaz;
while (sum > -1) {
index -= num;
if (tabukaz[index] == ']')
sum += num;
else if (tabukaz[index] == '[')
sum -= num;
}
return index;
}
int main () {
int tab[30000];
int tabukaz[30000];
int c;
int i = 0; int ukaz = 0;
unsigned char ch;
for (int i = 0; i < 30000; i++) {
tab[i] = 0;
tabukaz[i] = 0;
}
while ((c=getchar()) != EOF) {
ch = (unsigned char)c;
if (ch == '>' || ch == '<' || ch == '+' || ch == '-' || ch == '.' || ch == '[' || ch == ']')
{
tabukaz[ukaz] = ch;
}
switch (ch) {
case '>': i++; break;
case '<': i--; break;
case '+': tab[i]++;break;
case '-': tab[i]--; break;
case '.': putchar(tab[i]); break;
case '[':
if (tab[i]==0) {
ukaz = bla(tabukaz, ukaz, -1);
}
break;
case ']':
if (tab[i]!=0) {
ukaz = bla(tabukaz, ukaz, 1);
}
break;
default:
break;
}
ukaz++;
}
return 0;
}
This is the input in question (I tried to avoid the other text in the actual input (keep in mind everything down here is part of the input, even the unnecessary text) We were provided with a make file which will write the output into a text file, and compare it to a predefined text, the problem is my text file comes out as a binary file and I cant figure out why. The problem may be hidden in how I handle [ and ] as I didn't have that problem in the earlier tests without them
+++++ +++++ initialize counter (cell #0) to 10
[ use loop to set 70/100/30/10
> +++++ ++ add 7 to cell #1
> +++++ +++++ add 10 to cell #2
> +++ add 3 to cell #3
> + add 1 to cell #4
<<<< - decrement counter (cell #0)
]
> ++ . print 'H'
> + . print 'e'
+++++ ++ . print 'l'
. print 'l'
+++ . print 'o'
> ++ . print ' '
<< +++++ +++++ +++++ . print 'W'
> . print 'o'
+++ . print 'r'
----- - . print 'l'
----- --- . print 'd'
> + . print '!'
> . print '\n'
As a suggestion made by somebody I did this:
while ((c=getchar())!=EOF) {
ch = (unsigned char)c;
if (ch == '>' || ch == '<' || ch == '+' || ch == '-' || ch == '.' || ch == '[' || ch == ']')
{
tabukaz[ukaz]=ch;
stukaz++;
}
}
while (stukaz>0) {
switch (tabukaz[ukaz]) {
case '>': i++; break;
case '<': i--; break;
case '+': if(tab[i]==255) tab[i] = 0;
else tab[i]++;
break;
case '-': if (tab[i]==0) tab[i] = 255;
else tab[i]--;
break;
case '.': printf ("%c", tab[i]); break;
case '[':
if (tab[i]==0) {
ukaz = bla(tabukaz, ukaz, -1);
}
break;
case ']':
if (tab[i]!=0) {
ukaz = bla(tabukaz, ukaz, 1);
}
break;
default: break;
}
stukaz--;
ukaz++;
}
However the problem now extends to the tests before that, as it even outputs those as binary files, I'm thinking there's something wrong with the [ and ] code and thus it doesn't increment the fields properly printing unwanted characters, how this extended to tests without them only when putting another loop around it I have no idea.
EDIT: the problem with the above loop is not the while loop not going trough, the problem is that it will never get into the switch, any solution to that?
The test is wrong while scanning for a matching bracket.
while (sum > -1) {
index -= num;
if (tabukaz[index] == ']')
sum += num;
else if (tabukaz[index] == '[')
sum -= num;
}
You set num to 1 for a backwards scan, but to -1 for a forward scan.
case '[':
if (tab[i]==0) {
ukaz = bla(tabukaz, ukaz, -1);
}
break;
case ']':
if (tab[i]!=0) {
ukaz = bla(tabukaz, ukaz, 1);
}
break;
So the test should be (sum != 0) so it stops when the brackets are balanced from either direction. Of course, sum is initialized to 0, so I recommend a do { ... } while(); loop so the test is at the end.
Also, remember that you're incrementing the instruction pointer at the end of the loop.
ukaz++;
So you may want to set the pointer to bla(...) - 1, so the increment puts the pointer in the correct place.
You might also like to look at my own brainfuck interpreter, which is very similar to yours. One of my reviewers there gives an excellent explanation of optimizing the loop execution with a jump table.

Free array syntax and defining malloc

I am trying to free an array only if it contains something but I am heading a problem probably with syntax, because my code stores data in that array and when I change the file which the array reads from, it has to free that array because if I would like to store those characters in there again, it would just add them, not overwrite them.
The problem is this error in compiler: 0 [main] DNAA 2160 cygwin_exception::open_stackdumpfile: Dumping stack trace to DNAA.exe.stackdump
it does not work, I have no idea what is wrong.
void nacitanie(int *i, char *pole){
//some code....
int a, x=0;
char z;
//reading from file..
//condition if contains data, free it before running again
if (pole != NULL)
{
free (pole);
pole = NULL;
}
while( (z = getc(fp)) != EOF)
{
pole[*i] = z;
(*i)++;
}
for(a=0; a<*i; a++){
if(pole[a] == 'A' || pole[a] == 'C' || pole[a] == 'G' || pole[a] == 'T' || pole[a] == 'a' || pole[a] == 'c' || pole[a] == 'g' || pole[a] == 't'){
x++;
}else{
x--;
}
}
if(x==a){
printf("Sekvenciu sa podarilo nacitat\n");
fflush(stdout);
}else{
printf("Sekvencia nesplna podmienky\n");
fflush(stdout);
}
fclose(fp);
if(fclose(fp) == EOF)
printf("Subor sa nezatvoril");
}
malloc is in main function, where is reading function called
int main() {
int i=0;
char *pole = malloc(MAX);
//vstup z klavesnice
char c;
while(1)
{
switch(c = getchar())
{
case 'v':
trojica();
break;
case 'n':
nacitanie(&i, pole);
break;
case 'h':
histogram(&i, pole);
break;
MAX is defined as 1000 characters for that array

Errors in Tic-Tac-Toe Game

I've been trying to code a tic-tac-toe game in C except I've gotten some errors I don't understand. I know this still needs some work but right now I just want to run the program before I add to it. Can someone help me? Here's my code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int board[3][3] = {
{0, 0, 0},
{0, 0, 0},
{0, 0, 0}
};
int main (void)
{
int const user1 = 1;
int const user2 = 2;
char move[10];
while (! all_locations_filled()) {
printf("User-1, please enter your move:");
scanf("%s", move[10]);
if(valid_location(move[10]))
mark_location(user1, move[10]);
display_board(board[3][3]);
else if(won_the_game(user1)
printf("Congratulations User-1, You Won the Game!");
break;
else
printf("Invalid Move");
printf("User-2, please enter your move:");
scanf("%s", move[10]);
if(valid_location(move[10]))
mark_location(user2, move[10]);
display_board();
else if(won_the_game(user2)
printf("Congratulations User-2, You Won the Game!");
break;
else
printf("Invalid Move");
return 0;
}
bool valid_location(char str[10]) {
int strcmp(x, y);
if (strcmp(str[10], "upperLeft") == 0 || strcmp(str[10], "up") == 0 || strcmp(str[10], "upperRight") == 0 || strcmp(str[10], "left") == 0 || strcmp(str[10], "center") == 0 || strcmp(str[10], "right") == 0 || strcmp(str[10], "lowerLeft") == 0 || strcmp(str[10], "down") == 0 || strcmp(str[10], "lowerRight") == 0)
return true;
}
void mark_location(int userU, char str[10]) {
int strcmp(x, y);
if (strcmp(str[10], "upperLeft") == 0)
board[0][0] = userU;
else if (strcmp(str[10], "up") == 0)
board[0][1] = userU;
else if (strcmp(str[10], "upperRight") == 0)
board[0][2] = userU;
else if (strcmp(str[10], "left") == 0)
board[1][0] = userU;
else if (strcmp(str[10], "center") == 0)
board[1][1] = userU;
else if (strcmp(str[10], "right") == 0)
board[1][2] = userU;
else if (strcmp(str[10], "lowerLeft") == 0)
board[2][0] = userU;
else if (strcmp(str[10], "down") == 0)
board[2][1] = userU;
else if (strcmp(str[10], "lowerRight") == 0)
board [2][2] = userU;
}
char display_board(int array[][]) {
int i, j;
for (i=0; i<3; ++i)
for (j=0; j<3; ++j)
if (array[i][j] == 0)
print("-");
else if (array[i][j] == 1)
print("x");
else if (array[i][j] == 2)
print("o");
}
void all_locations_filled() {
int i, j;
for (i=0; i<3; ++i)
for (j=0; j<3; ++j)
if board[i][j] == 0
return false;
return true;
}
bool won_the_game(userU) {
int i, j;
if (board[0][j] == userU)
return true;
else if (board[1][j] == userU)
return true;
else if (board[2][j] == userU)
return true;
else if (board[i][0] == userU)
return true;
else if (board[i][1] == userU)
return true;
else if (board[i][2] == userU)
return true;
else
return false;
}
Here are the errors the compiler gives me:
tictactoe.c: In function ‘main’:
tictactoe.c:19: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
tictactoe.c:24: error: expected expression before ‘else’
tictactoe.c:115: error: expected declaration or statement at end of input
tictactoe.c:115: error: expected declaration or statement at end of input
if(valid_location(move[10]))
mark_location(user1, move[10]);
display_board(board[3][3]);
you have to use "{" and "}" because you have 2 lines.
Use move instead of move[10] in your scanf statement, and when you're passing it to functions. move refers to the array, move[10] just means the 10th position in that array.
Put braces {} around the code in your if / else blocks if they're more than a single line of code (or preferably always, but that's a style issue.)
I found some errors...
scanf("%s", move[10]);
What do you want to do here? If you want to read a string, use
scanf("%s", move );
If you want to read only one character in the 10th position of the array, use
scanf("%c", &move[9] );
Note that your array was declared as move[10], so it's positions go from move[0] to move[9]. Position move[10] is not valid.
Here:
if(valid_location(move[10]))
mark_location(user1, move[10]);
display_board(board[3][3]);
else if(won_the_game(user1)
printf("Congratulations User-1, You Won the Game!");
break;
else
printf("Invalid Move");
You probably meant:
if(valid_location(move[10]))
{
mark_location(user1, move[10]);
display_board(board[3][3]);
}
else if(won_the_game(user1)
{
printf("Congratulations User-1, You Won the Game!");
break;
}
else
printf("Invalid Move");
And here:
void all_locations_filled() {
int i, j;
for (i=0; i<3; ++i)
for (j=0; j<3; ++j)
if board[i][j] == 0
return false;
return true;
}
You forgot the () in the "if". It should be:
if (board[i][j] == 0)
Also, your functions must be declared before you call them. So, declare de functions before main.
You don't have to implement it there, just declare. For example:
void all_locations_filled();
int main (void)
{
...
}
In the last function:
bool won_the_game(userU)
you have to define the type of "userU".
You also forgot to close the brace "}" in the end of the main's while.
You are trying to scan an integer but the scanf argument expects an string (char array). Try %d instead of %s. Thats the Formatstring for Decimal numbers.
If you want to put more then one instruction after an if, you should close it in {}.
Otherwise, the compiler think that only the first is in-condition, and the rest should be done anyway.
scanf("%s", move); not scanf("%s", move[10]);
if(valid_location(move)) not if(valid_location(move[10]))
mark_location(user1, move); not mark_location(user1, move[10]);
if (strcmp(str, "upperLeft") == 0) not if (strcmp(str[10], "upperLeft") == 0)
etc. etc.
You don't do arrays in C by putting square brackets after each and every use of an array. You use the square bracket in basically two situations, you are declaring the array in which case the brackets contain the size of the array, you are accessing an element of the array in which case the brackets contain the index.
You probably won't want to hear this but there's plenty else wrong with your code. You probably need to read a book, and start a bit simpler.
After you've dealt with your compiler errors you might want to look at the function won_the_game which is reading uninitialised variables i and j and will probably give you "access violation" errors as i and j are likely to be out of bounds.
In addition your logic is wrong since obviously you don't win by just occupying one position.

Resources