AddressSanitizer:DEADLYSIGNAL when trying to use a user input - c

here is the code that i have:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <assert.h>
#include <time.h>
const int Win = 0, Lose = 1, Draw = 2;
const int Rock = 0, Paper = 1, Scissors = 2;
int input(int n, char i[n]){
if (i[0] == 'R' || i[0] == 'r') return Rock;
else if (i[0] == 'P' || i[0] == 'p') return Paper;
else if (i[0] == 'S' || i[0] == 's') return Scissors;
else return -1;
}
int game(int n){
srand(time(NULL));
int r = rand() % 2;
if (r == n) return Draw;
else if (r == 0 && n == 1) return Win;
else if (r == 0 && n == 2) return Lose;
else if (r == 1 && n == 0) return Lose;
else if (r == 1 && n == 2) return Win;
else if (r == 2 && n == 0) return Win;
else if (r == 2 && n == 1) return Lose;
else return 0;
}
void print(int game){
if (game == Draw && input == Rock) printf ("i chose rock, its a draw\n");
else if (game == Draw && input == Paper) printf ("i chose paper, its a draw\n");
else if (game == Draw && input == Scissors) printf ("i chose scissors, its a draw\n");
else if (game == Win && input == Rock) printf ("i chose scissors, you win\n");
else if (game == Win && input == Paper) printf ("i chose rock, you win\n");
else if (game == Win && input == Scissors) printf ("i chose paper, you win\n");
else if (game == Lose && input == Rock) printf ("i chose paper, you lose\n");
else if (game == Lose && input == Paper) printf ("i chose scissors, you lose\n");
else printf ("i chose rock, you lose\n");
}
// void checkInput(){
// assert(input(1, 'R') == 1);
// assert(input(1, 'r') == 1);
// assert(input(1, 'P') == 2);
// assert(input(1, 'p') == 2);
// assert(input(1, 'S') == 3);
// assert(input(1, 's') == 3);
// printf("all tests pass\n");
// }
int main(){
setbuf(stdout, NULL);
char *j[1];
for(int a = 0; a >= 0; a++){
printf("pick rock, paper, scissors (R/P/S) 'e' to exit\n");
scanf("%s", &*j[0]);
if (j[0] == 'e') break;
print(game(input(strlen(j[0]), j[0])));
}
return 0;
}
when i run it prints out the line and lets me input something after which it gives me this error
pick rock, paper, scissors (R/P/S) 'e' to exit
R
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4029==ERROR: AddressSanitizer: SEGV on unknown address 0x7f5ca33d6787 (pc 0x7f5ca328ffdd bp 0x7ffca0431550 sp 0x7ffca0430e70 T0)
==4029==The signal is caused by a WRITE memory access.
#0 0x7f5ca328ffdc (/lib/x86_64-linux-gnu/libc.so.6+0x6cfdc)
#1 0x7f5ca329f12b (/lib/x86_64-linux-gnu/libc.so.6+0x7c12b)
#2 0x4a724c (/home/student/Documents/extra+0x4a724c)
#3 0x4a734e (/home/student/Documents/extra+0x4a734e)
#4 0x512a5e (/home/student/Documents/extra+0x512a5e)
#5 0x7f5ca3244b96 (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
#6 0x419e19 (/home/student/Documents/extra+0x419e19)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (/lib/x86_64-linux-gnu/libc.so.6+0x6cfdc)
==4029==ABORTING
how can i stop this from happening as this error means nothing to me, and cant see anything that could be wrong with it. I know i have pasted a lot of code but i figure you need to see all of it to have an idea where it is crashing from.

You need to turn on compiler warnings: You have some significant problems in your code.
The lines of the form:
else if (game == Draw && input == Paper) printf ("i chose paper, its a draw\n");
are comparing input (which is a function pointer) to an integer. The compiler will warn you about this problem if you let it. Do that, try again, and ask for help if you need it.
Also, you are not using scanf properly. Look for questions on Stack Overflow about scanf, and print the value you get back from scanf in order to debug your program.
Best of luck, and don't hesitate to ask another question when you get stuck.

Related

Rock Paper .. game

This code runs just fine.
but there is some minor mistake in the program. I don't know what's the problem 'cause it's like I keep on winning the game and the computer just loses the game every time. 3
the game Rock, Paper, Scissors. My problem is if I execute the program, I just keep winning.I need the game to let the computer win. How can I rectify this?
#include <stdio.h
#include <time.h>
int Random(int n) {
srand(time(NULL));
printf("%d\n", rand() % 3); }
int greater(char ch1, char ch2) {
if (ch1 == ch2)
{
return -1;
}
else if ((ch1 == 'R') && (ch2 == 's'))
{
return 1;
}
else if ((ch2 == 'R') && (ch1 == 's'))
{
return 0;
}
else if ((ch1 == 's') && (ch2 == 'p'))
{
return 1;
}
else if ((ch2 == 's') && (ch1 == 'p'))
{
return 0;
}
else if ((ch1 == 'p') && (ch2 == 'r'))
{
return 1;
}
else if ((ch2 == 'p') && (ch1 == 'r'))
{
return 0;
}
}
int main() {
char playerchar, computerchar, a;
int playerscore = 0, compscore = 0, b;
char ch[] = {'R', 'P', 'S'};
printf("\n");
printf("~~~~~Welcome to the Rock, Paper, Scissors Game~~~~~\n\n");
printf("Choose a number\n 1. for Rock\n 2. for Paper\n 3. for Scissiors\n");
for (int i = 0; i < 3; i++)
{
printf("Player's Turn :\n");
scanf("%d", &b);
getchar();
playerchar = ch[b - 1];
printf("You chose %c\n", playerchar);
printf("Computer's Turn :\n");
b = Random(3) + 1;
computerchar = ch[b - 1];
printf("Computer chose %c\n", computerchar);
if ((greater(computerchar, playerchar) == 1))
{
compscore += 1;
printf("Computer got it!\n\n");
}
else if ((greater(computerchar, playerchar) == -1))
{
compscore += 1;
playerscore += 1;
printf("It's a draw\n");
}
else
{
playerscore += 1;
printf("You got it!\n\n");
}
printf("You : %d\nComputer: %d\n\n",playerscore,compscore);
}
if (compscore > playerscore)
{
printf("Computer win the game!\n\n");
}
else if (playerscore > compscore)
{
printf("You win the game!\n\n");
}
else
{
printf("The game is draw\n");
}
return 0;}
There's really no point complex if statements for determining the winner. Just realize that rock paper scissors is basically just a directed cycle graph.
// Returns winner in rock paper scissors
// 0 - Rock, 1 - Paper, 2 - Scissors
// Return values:
// 0 - draw
// 1 - a win, b loose
// -1 - b win, a loose
int rps(int a, int b) {
if(a == b) return 0;
return (a+1) % 3 == b ? -1 : 1;
}
Normal rps (rock, paper, scissors) has 3 nodes in the graph. This can actually easily be generalized to n nodes. The algorithm works like this. Start on node a. If it's the same as b, then it's a draw. Otherwise, check how many steps it is required to to go around the graph to get to b and determine the winner depending on if the number of steps is even or odd.
int rpsn(int a, int b, int n) {
if(a == b) return 0;
int steps = 0;
while((a+steps) % n != b) steps++;
return steps % 2 ? -1 : 1;
}
Read about Rock, Paper, Scissors, Lizard, Spock for a 5 node version.
I'm fairly confident that the loop could be exchanged for a single clever math operation, but I'm having a brain freeze at the moment. I'll update the post if I find it.
EDIT:
I found a way. Here is a very short rps function with no loops for arbitrary n:
// Returns the number of steps required to go from a to b
int steps(int a, int b, int n) {
return (n+b-a) % n;
}
int rpsn(int a, int b, int n) {
if(a == b) return 0;
return steps(a,b,n) % 2 ? -1 : 1;
}
The reason for doing (n+b-a) % n instead of (b-a) % n is that we need the left operand of % to be nonnegative.
First of all, srand should be called just once at the beginning of the program. You call it on every call of Random().
But the bigger issue is that your function Random() does not return anything, it just prints the value. This should have grnerated a warning in your compiler. This probably means that Random always returns 0.
To fix the problem, do return rand() % 3; instead of printing it.

How to let player chose to be X or O as well as an option to play the game again?

So I need some help in this Tic-Tac-Toe game. I have almost everything working correctly I just need to add on some features. Those features include: 1.) allowing the player to choose whether they want to play as X or O in the game, and 2.) giving the option for the players to replay the game if they wish. I've gotten the base mechanics of the game to work out nicely, I just can't figure out how to add these features into the code. I've started to "lay the foundation" for the first feature (giving the player the option to choose their mark). (Honestly, I'm just really tired from studying for the past 48hrs for finals and I could really use a helping hand here). Here is my full code:
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#include <stdio.h>
#include <conio.h>
int checkwin(char gridspace[]);
void gameboard(char gridspace[]);
int gameLoop(int choice, int player, char gridspace[], char mark);
void main(void)
{
char grid[10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int player = 1, victory, choice;
char mark, player1, player2;
int markchoice;
do // game loop start
{
gameboard(grid); // draws the game board
if (player % 2) // player turn conditional
{
player = 1;
}
else
{
player = 2;
}
printf("Player 1, choose which mark you would like to play as (1=X or 2=O)\n"); // asks the player to choose a mark
scanf("%c", &markchoice);
if (markchoice == 1) // mark choice conditional
{
mark = 'X';
}
else
{
mark = 'O';
}
printf("Player %d, enter the number of the place you wish to place your mark: ", player); // asks the player to place their mark on a space
scanf("%d", &choice);
if (player == 1) // mark type (X or O) placement conditional
{
mark;
}
else
{
mark;
}
gameLoop(choice, player, grid, mark); // calls the main game function that houses the conditionals
victory = checkwin(grid); // checks the state of the game (if its in progress, a draw, or a player has achieved victory.
player++;
} while (victory == -1); //end of game loop
gameboard(grid); // redraws the game board
if (victory == 1) // conditional that breaks the game loop and gives a result (victory or draw)
{
printf("==>\aPlayer %d win ", --player);
}
else
{
printf("==>\aGame draw");
getch();
}
return 0;
} // end of main
int gameLoop(int choice,int player, char gridspace[], char mark) // function for game loop
decisionals
{
if (choice == 1 && gridspace[1] == '1')
gridspace[1] = mark;
else if (choice == 2 && gridspace[2] == '2')
gridspace[2] = mark;
else if (choice == 3 && gridspace[3] == '3')
gridspace[3] = mark;
else if (choice == 4 && gridspace[4] == '4')
gridspace[4] = mark;
else if (choice == 5 && gridspace[5] == '5')
gridspace[5] = mark;
else if (choice == 6 && gridspace[6] == '6')
gridspace[6] = mark;
else if (choice == 7 && gridspace[7] == '7')
gridspace[7] = mark;
else if (choice == 8 && gridspace[8] == '8')
gridspace[8] = mark;
else if (choice == 9 && gridspace[9] == '9')
gridspace[9] = mark;
else
{
printf("Invalid move, input a different number.");
player--;
getch();
}
return 1;
}// end of game loop function
int checkwin(char gridspace[]) // check win function
{
if (gridspace[1] == gridspace[2] && gridspace[2] == gridspace[3])
return 1;
else if (gridspace[4] == gridspace[5] && gridspace[5] == gridspace[6])
return 1;
else if (gridspace[7] == gridspace[8] && gridspace[8] == gridspace[9])
return 1;
else if (gridspace[1] == gridspace[4] && gridspace[4] == gridspace[7])
return 1;
else if (gridspace[2] == gridspace[5] && gridspace[5] == gridspace[8])
return 1;
else if (gridspace[3] == gridspace[6] && gridspace[6] == gridspace[9])
return 1;
else if (gridspace[1] == gridspace[5] && gridspace[5] == gridspace[9])
return 1;
else if (gridspace[3] == gridspace[5] && gridspace[5] == gridspace[7])
return 1;
else if (gridspace[1] != '1' && gridspace[2] != '2' && gridspace[3] != '3' &&
gridspace[4] != '4' && gridspace[5] != '5' && gridspace[6] != '6' && gridspace[7]
!= '7' && gridspace[8] != '8' && gridspace[9] != '9') // if all spaces are filled but no
three match then the game is a draw
return 0;
else // if no three spaces match and empty spaces still exist then the game is still in
progress.
return -1;
} // end of check win function
void gameboard(char gridspace[]) // game board function.
{
system("cls");
printf("\n\n\tTic Tac Toe\n\n");
printf("Enter a number for where you wish to place your mark");
printf("Player 1 (X) - Player 2 (O)\n\n\n");
printf(" | | \n");
printf(" %c | %c | %c \n", gridspace[1], gridspace[2], gridspace[3]);
printf("_____|_____|_____\n");
printf(" | | \n");
printf(" %c | %c | %c \n", gridspace[4], gridspace[5], gridspace[6]);
printf("_____|_____|_____\n");
printf(" | | \n");
printf(" %c | %c | %c \n", gridspace[7], gridspace[8], gridspace[9]);
printf(" | | \n\n");
} // end of board drawing funciton.
Any and all help would be greatly appreciated. So thank you in advance!
to allow multiple rounds you can add another while loop outside the game one in order to reset all the stats and restart the game until player decides to stop(you can use a scanf to check for y/n).

RockPaperScissor game not getting expected result - C programming

I was writing c program on rock paper and scissor game but could not get the expected result.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
char player[50], choice[10];
puts("Enter your name: ");
gets(player);
int player1 = 0, comp = 0;
for (int i = 0; i < 3; i++)
{
srand(time(NULL));
printf("%s: ", player);
scanf("%s", choice);
int computer = rand()%3;
if (computer == 0){
printf("computer: rock\n");
} else if(computer == 1){
printf("computer: paper\n");
}else{
printf("computer: scissor\n");
}
if (computer == 0 && choice == "paper"){
player1++;
}else if (computer == 0 && choice == "rock"){
continue;
}else if (computer == 0 && choice == "scissor"){
comp++;
}else if (computer == 1 && choice == "paper"){
continue;
}else if (computer == 1 && choice == "rock"){
comp++;
}else if (computer == 1 && choice == "scissor"){
player1++;
}else if (computer == 2 && choice == "paper"){
player1++;
}else if (computer == 2 && choice == "rock"){
comp++;
}else if (computer == 2 && choice == "scissor"){
continue;
}else {
printf("Invalid Entry.");
}
printf("\n");
}
if (player1 > comp){
printf("%s wins.", player);
}else if (player1 == comp) {
printf("%s and computer draws.", player);
}else{
printf("%s loses.", player);
}
return 0;
}
The program works but I am not getting the expecteed result in all 3 runs of the for loop I get only invalid entry as output due to which I can't count the score and the result as both player and comp variable are idle due to this.
output:
Enter your name:
Sam
Sam: rock
computer: scissor
Invalid Entry.
Sam: scissor
computer: scissor
Invalid Entry.
Sam: paper
computer: paper
Invalid Entry.
Sam and computer draws.
I have checked to best my skill and could not find any mistake I don't know why if else-if is acting weirdly, Help me to get correct output and explain me what the problem and where the mistake is.
You need to comare strings using strcmp from <string.h>. Note that strcmp returns 0 if the strings match.
#include <string.h>
int strcmp(const char *str1, const char *str2);
For example you would have to replace choice == "paper" with !strcmp(choise, "paper").
And you should also use fgets instead of gets.
char player[50];
fgets(str, 50, stdin);
Alternatively you could use and scanf (inferior in many cases).
char player[50];
scanf("%49[^\n]", player); /* take \0 into account */

Another text based adventure game; while loop battle system

Thank you to anyone who tries to help me with this!
So what should happen here is that if you run this, and you pick class choice 1,2 or 3, then when you go into the battle your attacks are different etc.
I'm making it so that you have to win rock paper scissors to be able to attack, so if the computer wins it attacks you.
For class choice 1, this works, however for the other two is doesn't and I'm lost as to why.
I'm very new to c so sorry if I'm missing something obvious!
For example if you pick class choice 3, guardian, and you win or lose the rock paper scissors game, nothing happens at all, where as it should let you attack or him attack
#include<stdio.h>
#include<string.h>
int i;
int playerschoice, compchoice;
main()
{
int i;
int choice1,choice2;
int class_choice,warrior,rogue,guardian;
int HoodMan_Health = 30;
int HoodMan_HealthCurrent;
int HoodManAtk = 25;
int HoodManDef = 15;
int RogueAtk = 100;
int RogueDef = 10;
int WarriorAtk = 50;
int WarriorDef = 50;
int GuardianAtk = 10;
int GuardianDef = 100;
int health = 100;
int currenthealth;
int difficulty;
int level;
printf("\n1.Rogue [100atck 10def]\n\n2.Warrior [50atck 50def]\n\n3.Guardian [10atck 100def]\n");
printf("\nYour choice?\t");
scanf("%i",&class_choice);
if (class_choice == 1 || class_choice == 2 ||class_choice == 3)
{
printf("\nLets play...\n\n");
system ("PAUSE");
}
else
{
printf("\nThat was not a choice\n");
return(0);
}
while ( (currenthealth>0)&&(HoodMan_Health>0) ) // while both healths are above zero do this battle
rockpaperscissors();
{
if (((playerschoice == 1)&&(compchoice == 3)) || ((playerschoice == 2)&&(compchoice == 1)) || ((playerschoice == 3)&&(compchoice == 1)))
{
printf("You attack the hooded man\n");
if (class_choice == 1)
{
HoodMan_Health=HoodMan_Health-(RogueAtk*0.5+HoodManDef*0.25);
printf("The Hooded Man's health is now %i\n\n",HoodMan_Health);
}
else if (class_choice == 2)
{
HoodMan_Health=HoodMan_Health-(WarriorAtk*0.5+HoodManDef*0.25);
printf("The Hooded Man's health is now %i\n\n",HoodMan_Health);
}
else if (class_choice == 3)
{
HoodMan_Health=HoodMan_Health-(GuardianAtk*0.5+HoodManDef*0.25);
printf("The Hooded Man's health is now %i\n\n",HoodMan_Health);
}
}
else if (((playerschoice == 3)&&(compchoice == 1)) || ((playerschoice == 1)&&(compchoice == 2)) || ((playerschoice == 1)&&(compchoice == 3)))
{
printf("The Hooded Man attacks you\n");
if (class_choice == 1)
{
currenthealth=currenthealth-(HoodManAtk+RogueDef*0.5);
printf("Your health is now %i\n\n\n",currenthealth);
}
else if (class_choice == 2)
{
currenthealth=currenthealth-(HoodManAtk+WarriorDef*0.5);
printf("Your health is now %i\n\n\n",currenthealth);
}
else if (class_choice == 3)
{
currenthealth=currenthealth-(HoodManAtk+GuardianDef*0.5);
printf("Your health is now %i\n\n\n",currenthealth);
}
}
}
if (currenthealth<0)
{
printf("You died\n");
return (0);
}
else
{
printf("You killed the hooded man\n");
}
}
void rockpaperscissors()
{
printf("Enter 1 for Rock, 2 for Paper and 3 for Scissors\n");
scanf("%i",&playerschoice);
if ( playerschoice == 1 )
{
printf("You are going with: Rock...\n");
}
else if ( playerschoice == 2 )
{
printf("You are going with: Paper...\n");
}
else if ( playerschoice == 3 )
{
printf("You are going with: Scissors...\n");
}
else if ( playerschoice != 1||2||3)
{
printf("that was not a choice");
return(0);
}
// initialize random seed: //
srand (time(NULL));
// set compchoice to random number from 1 to 3 //
compchoice=rand() %3+1;
if (compchoice == 1)
{
printf("\nThe computer is going with: Rock...\n\n");
}
else if (compchoice == 2)
{
printf("\nThe computer is going with: Paper...\n\n");
}
else if (compchoice == 3)
{
printf("\nThe computer is going with: Scissors...\n\n");
}
{
if (((playerschoice == 1)&&(compchoice == 3)) || ((playerschoice == 2)&&(compchoice == 1)) || ((playerschoice == 3)&&(compchoice == 1)))
{
printf("you win\n");
}
else if (((playerschoice == 3)&&(compchoice == 1)) || ((playerschoice == 1)&&(compchoice == 2)) || ((playerschoice == 1)&&(compchoice == 3)))
{
printf("you lose\n");
}
else if (((playerschoice == 1)&&(compchoice == 1)) || ((playerschoice == 2)&&(compchoice == 2)) || ((playerschoice == 3)&&(compchoice == 3)))
{
printf("it's a draw\n");
}
}
}
Here are the chief errors in your program:
To use: system("pause"); you should include <windows.h>
To use: time(NULL) you should include <time.h>
string.h isn't really required in your program.
You haven't initialized currenthealth which can lead to unpredictable outcome.
You have made variables like health and HoodMan_HealthCurrent but are not using them.
Call to rockpaperscissors() should be inside the while block.
Putting it outside makes the loop infinite and the code in the block never gets executed!
If you want to use floating point arithmetic like HoodManDef*0.25 you should declare it as float or else it will be rounded off.
The condition else if ( playerschoice != 1||2||3) is wrong(always true) and redundant(The above three conditions imply that playerschoice will not be 1,2 or 3 ).
A simple else will suffice.
rockpaperscissors() is a void function.You cannot return(0);. Use a simple return; instead.
You don't have to use srand() every time you call the function.You can simply use it at the start of program or when each game starts(if you plan to make it re playable without restarting) .
Some Problems with the game:
You are adding character's defense to opponent's attack! i.e the more defense i have , the more powerful my opponent will become . You should subtract instead.
Defense of warrior and Guardian is so much that their health won't decrease even if attacked by the hoodman.

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