Pointer assignment using malloc going wrong [closed] - c

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Please feel free to copy paste and try it out, it stops working halfway through function handget when individual hand is assigned a space in memory
/*
* A program that is meant to classify five-card poker hands.
*Is still in progress
*/
#include<stdio.h>
#include<math.h>
#include<ctype.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#define SEED 7
#define SIZE 5
/*
*
*/
typedef enum suits {
clubs,
diamonds,
hearts,
spades
} suits;
typedef enum values {
zero,
one, // not used, but ensures numerical values correspond
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
jack,
queen,
king,
ace
} values;
typedef struct cards {
suits suit;
values value;
} cards;
int islegal(cards *hand, int nr_of_cards);
/* Given any number of cards, determines whether any duplicates
* or false cards are present or not. If so, returns 0, otherwise 1.
*/
int flop(cards **handPtr);
/* Asks the user to input a hand of cards;
* returns the number of cards being input
*/
int *rawtoflop (cards *handPtr, int nr_of_cards);
int hander(cards **handPtr,int counter);
int handget(cards **playerhands,cards *thishands, int handsize);
void printsuit(suits thissuit);
/* Prints the enum-type suits
*/
void printvalue(values thisvalue);
/* Prints the enum-type values
*/
void printhand(cards *hand, int nr_of_cards);
/* Prints a hand of cards without further processing
*/
int main(void) {
cards *thishand, *playerhands;
flop(&thishand);
printhand(thishand,6);
handget(&playerhands,thishand,6);
return 0;
}
int islegal(cards *hand, int nr_of_cards) {
int i, fulldeck[4][13]={0};
int current_value, current_suit;
cards *current_card = hand;
int legal = 1;
for (i=0; i<nr_of_cards; i++) {
current_value = (int) (*current_card).value;
current_suit = (*current_card).suit;
// if the current card has value zero, it is not a valid hand
if (current_value==0) {
legal = 0;
break;
}
//check if the current card already appears, if yes invalid hand, if no,
//change the flag for that card in the full deck.
//Since (two) will correspond to fulldeck[.][0] there is a -2 offset.
if ( (fulldeck[current_suit][current_value - 2]) > 0 ) {
legal = 0;
break;
} else {
fulldeck[current_suit][current_value - 2]++;
}
current_card++;
}
return legal;
}
int flop(cards **handPtr) {
int i,*q=NULL,n=NULL;
int j[5]={0,0,0,0,0};
int k[5]={1,1,1,1,1},nr_of_cards = 5;//for more/less cards CHANGE HERE!
char rawsuit, rawcard[4];
// allocate the required amount of memory for your cards
(*handPtr) = (cards *) malloc(nr_of_cards * sizeof(cards));
n=memcmp(j,k,sizeof(j));
while(n!=0) {
printf("Please input the five cards on the table: ");
q=rawtoflop(*handPtr,nr_of_cards);
for (i=0;i<nr_of_cards;i++) {
j[i]=*(q+i);
}
n=memcmp(j,k,sizeof(j));
}
free(&handPtr);
return nr_of_cards;
}
int *rawtoflop (cards *handPtr, int nr_of_cards){
int i,m[5],*mPtr;
char rawsuit, rawcard[4];
mPtr=m;
// ask for the cards
for (i=0; i<nr_of_cards; i++)/* do */{
scanf("%3s", &rawcard);
rawsuit = rawcard[0];
if (rawcard[1]=='1') {
if (rawcard[2]=='0') {
(handPtr)[i].value = ten;
} else {
(handPtr)[i].value = zero;
}
} else if (rawcard[1]=='2') {
(handPtr)[i].value = two;
} else if (rawcard[1]=='3') {
(handPtr)[i].value = three;
} else if (rawcard[1]=='4') {
(handPtr)[i].value = four;
} else if (rawcard[1]=='5') {
(handPtr)[i].value = five;
} else if (rawcard[1]=='6') {
(handPtr)[i].value = six;
} else if (rawcard[1]=='7') {
(handPtr)[i].value = seven;
} else if (rawcard[1]=='8') {
(handPtr)[i].value = eight;
} else if (rawcard[1]=='9') {
(handPtr)[i].value = nine;
} else if (rawcard[1]=='J') {
(handPtr)[i].value = jack;
} else if (rawcard[1]=='Q') {
(handPtr)[i].value = queen;
} else if (rawcard[1]=='K') {
(handPtr)[i].value = king;
} else if (rawcard[1]=='A') {
(handPtr)[i].value = ace;
} else {
(handPtr)[i].value = zero;
}
switch (rawsuit) {
case 'h':
(handPtr)[i].suit = hearts;
break;
case 'd':
(handPtr)[i].suit = diamonds;
break;
case 'c':
(handPtr)[i].suit = clubs;
break;
case 's':
(handPtr)[i].suit = spades;
break;
default:
(handPtr)[i].value = zero;
}
m[i]=(islegal(handPtr,i+1));
}
return mPtr;
}
int hander(cards **handPtr,int counter) {
int i, nr_of_cards = 2;
char rawsuit, rawcard[4];
if(counter==0){
// allocate the required amount of memory for your cards
(*handPtr) = (cards *) malloc(nr_of_cards * sizeof(cards));
}
// ask for the cards
for (i=0; i<nr_of_cards; i++) do {
scanf("%3s", &rawcard);
rawsuit = rawcard[0];
if (rawcard[1]=='1') {
if (rawcard[2]=='0') {
(*handPtr)[i].value = ten;
} else {
(*handPtr)[i].value = zero;
}
} else if (rawcard[1]=='2') {
(*handPtr)[i].value = two;
} else if (rawcard[1]=='3') {
(*handPtr)[i].value = three;
} else if (rawcard[1]=='4') {
(*handPtr)[i].value = four;
} else if (rawcard[1]=='5') {
(*handPtr)[i].value = five;
} else if (rawcard[1]=='6') {
(*handPtr)[i].value = six;
} else if (rawcard[1]=='7') {
(*handPtr)[i].value = seven;
} else if (rawcard[1]=='8') {
(*handPtr)[i].value = eight;
} else if (rawcard[1]=='9') {
(*handPtr)[i].value = nine;
} else if (rawcard[1]=='J') {
(*handPtr)[i].value = jack;
} else if (rawcard[1]=='Q') {
(*handPtr)[i].value = queen;
} else if (rawcard[1]=='K') {
(*handPtr)[i].value = king;
} else if (rawcard[1]=='A') {
(*handPtr)[i].value = ace;
} else {
(*handPtr)[i].value = zero;
}
switch (rawsuit) {
case 'h':
(*handPtr)[i].suit = hearts;
break;
case 'd':
(*handPtr)[i].suit = diamonds;
break;
case 'c':
(*handPtr)[i].suit = clubs;
break;
case 's':
(*handPtr)[i].suit = spades;
break;
default:
(*handPtr)[i].value = zero;
}
} while (!islegal(*handPtr, i+1));
return nr_of_cards;
}
int handget(cards **playerhand,cards *thishands, int handsize) {
cards *player=NULL,*individualhand=NULL;
int nr_players=1;
(*playerhand) = (cards *) malloc(7*sizeof(cards));
memcpy(*playerhand,thishands,handsize*sizeof(cards));
printf("Please enter the cards for player 1: ");
hander(&player,0);
memcpy(*playerhand+5,player,7*sizeof(cards));
printf("1 we made it this far chaps!!!\n");
individualhand =(cards *) malloc(7*sizeof(cards));//THIS IS WHERE IT ALL GOES WRONG!!
printf("2 we made it this far chaps!!\n");
return nr_players;
}
void printsuit(suits thissuit) {
switch (thissuit) {
case diamonds:
printf("d");
break;
case clubs:
printf("c");
break;
case hearts:
printf("h");
break;
case spades:
printf("s");
break;
}
return;
}
void printvalue(values thisvalue) {
switch (thisvalue) {
case two:
printf("2");
break;
case three:
printf("3");
break;
case four:
printf("4");
break;
case five:
printf("5");
break;
case six:
printf("6");
break;
case seven:
printf("7");
break;
case eight:
printf("8");
break;
case nine:
printf("9");
break;
case ten:
printf("10");
break;
case jack:
printf("J");
break;
case queen:
printf("Q");
break;
case king:
printf("K");
break;
case ace:
printf("A");
break;
}
return;
}
void printhand(cards *hand, int nr_of_cards) {
int i;
for (i=0; i<nr_of_cards; i++) {
printsuit((hand[i]).suit);
printvalue((hand[i]).value);
printf(" ");
}
printf("\n");
return;
}

You allocate enough space for 7 cards:
(*playerhand) = (cards *) malloc(7*sizeof(cards));
Then you copy seven cards into *playerhand+5:
memcpy(*playerhand+5,player,7*sizeof(cards));
So you get a buffer overflow. *playerhand+5 is the same as &(*playerhand)[5]. So you're copying 7 cards into the fifth place in an array with enough capacity for 7 cards.
That's one problem of using magic number. I can't guess what this "5" means if you don't give it a name (nor why 7 cards).

Actually the problem is not that you're copying TO thishands but that you are copying FROM thishands. You allocated 5*sizeof(cards) to thishands,but when calling handget, you're calling it with handget(&playerhands,thishand,6);. The last argument is 6, and therein lies your problem.
Get rid of all these magic numbers. Instead make them (and this is strictly because you seem to be using C not C++) #defines. That way you have a consistent number to work with.

Related

Segmentation fault on assigning int

I am following the video series "Coding a Rogue/Nethack clone in c" and getting a segfault despite the fact that the creator isn't.
This is using ncurses and the menu library.
gdb says it's in the function handleInput, when I try to set the x and y.
Pos* handleInput(int input, Player* user) {
Pos * newPosition;
newPosition = malloc(sizeof(Pos));
switch (input)
{
/* move up */
case 'w':
case 'W':
newPosition->y = user->pos->y - 1;
newPosition->x = user->pos->x;
break;
/* move down */
case 's':
case 'S':
newPosition->y = user->pos->y + 1;
newPosition->x = user->pos->x;
break;
/* move left */
case 'a':
case 'A':
newPosition->y = user->pos->y;
newPosition->x = user->pos->x - 1;
break;
/* move right */
case 'd':
case 'D':
newPosition->y = user->pos->y; // Segfault here
newPosition->x = user->pos->x + 1;
default:
break;
Some typedefs:
typedef struct Level {
int level;
char** tiles;
int numRooms;
struct Player* user;
struct Room** room;
struct Monster** Mons;
int numMons;
} Level;
typedef struct Pos {
int x;
int y;
} Pos;
typedef struct Player {
Pos* pos;
int atk;
int maxHP;
int xp;
int gold;
int health;
} Player;
typedef struct Monster {
char string[2];
char symbol;
int alive;
int health;
int attack;
int speed;
int defense;
int pathfinding;
Pos* pos;
} Monster;
And my game function:
int gameLoop()
{
int ch;
Pos* newPosition;
Level * level;
level = createLevel(1);
Player* user = level->user;
printGameHud(level);
/* main game loop */
while ((ch = getch()) != 'q')
{
printGameHud(level);
newPosition = handleInput(ch, user);
checkPosition(newPosition, level);
moveMonster(level);
move(level->user->pos->y, level->user->pos->x);
if (level->user->health <= 0)
{
return -1;
}
}
return 1;
}
Finally, my menu function, which seems to be where this started:
void menuLoop () {
int choice;
while (true) {
char* choices[] = {"Start", "Exit"};
choice = mainMenu(2, choices);
switch (choice) {
case START_GAME:
gameLoop();
clear();
break;
case QUIT_GAME:
return;
}
}
}
int closeMenu(int numItems, MENU* menu, ITEM** items){
unpost_menu(menu);
free_menu(menu);
for (int i = 0; i < numItems; i++) {
free_item(items[i]);
}
return 1;
}
int mainMenu(int numItems, char* items[]) {
int c, i, value;
MENU* menu;
ITEM* current;
ITEM** menuItems = malloc(sizeof(**menuItems) * numItems);
for (i = 0; i < numItems; i++) {
menuItems[i] = new_item(items[i], "");
}
menuItems[i] = (ITEM*)NULL;
menu = new_menu((ITEM**)menuItems);
post_menu(menu);
refresh();
while (true) {
c = getch();
switch(c){
case KEY_DOWN:
menu_driver(menu, REQ_DOWN_ITEM);
break;
case KEY_UP:
menu_driver(menu, REQ_UP_ITEM);
break;
case 10:
current = current_item(menu);
value = item_index(current);
closeMenu(numItems, menu, menuItems);
return value;
}
}
}

how to switch between players with enum from .h?

Does anyone know why when I run this code it goes for P2_TURN and how to make this enum active that when P2 move then P1 goes and whoever win the correct statement will be given from print_status()… also is there an easier/cleaner way to assign the winner. At the void process_move(struct game* p_game_info) is there a way to replace digits 0-8 with user input without switch case….Sorry for being a bit chaotic with this query but it’s almost 4 in the morning so hope you’ll forgive me….
game.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "game.h"
void play_game()
{
struct game *p_game_info = 0;
p_game_info = malloc(sizeof(struct game));
initialise_game (p_game_info, "John", "Annie");
draw_banner();
display_board(p_game_info->board);
system("cls");
display_board_positions ();
draw_banner();
process_move( p_game_info);
display_board(p_game_info->board);
print_status ( p_game_info );
}
void initialise_game(struct game* p_game_info, char* name1, char* name2)
{
for (int r=0; r<3; r++)
for(int c=0; c<3; c++)
p_game_info->board[r][c] = SPACE;
display_board_positions ();
p_game_info->status=P1_TURN;
// p_game_info->finished = False;
strncpy(p_game_info->playerNames[0], name1,MAX_NAME_LEN);
strncpy(p_game_info->playerNames[1], name2,MAX_NAME_LEN);
}
void draw_banner(){
printf("---------------\n");
printf(" GAME STATUS \n");
printf("---------------\n");
}
void display_board( char board[3][3]){
printf("---------------\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf(" %c ", board[i][j]);
if (j != 2)
printf("|");
}
if (i != 2)
printf("\n-----------");
printf("\n");
}
printf("---------------\n");
}
void print_status (struct game*p_game_info ){
if ((p_game_info->finished=False)&&
(p_game_info->status=P1_TURN))
{
printf("John's Turn\n");
}
else if ((p_game_info->finished=False)&&
(p_game_info->status=P2_TURN))
{
printf("Annie's Turn\n");
}
else if
(p_game_info->status==P1_WON)
{
printf( "Well done John, you have won\n");
}
else if
(p_game_info->status==P2_WON)
{
printf("Well done Annie, you have won\n");
}
else if
(p_game_info->status==DRAW)
{
printf("Game Over It is a draw\n");
}
}
void display_board_positions (){
int count = 0;
printf("---------------\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf(" %d ", count);
count++;
if (j != 2)
printf("|");
}
if (i != 2)
printf("\n-----------");
printf("\n");
}
printf("---------------\n");
}
void process_move(struct game* p_game_info){
if (p_game_info->status==P1_TURN){
printf("enter number for 'X' from 0-8\n");
char ckey = (char) getchar();
switch (ckey){
case '0':
if(p_game_info->board[0][0]==SPACE){
p_game_info->board[0][0]=X_SYMBOL;
}
break;
case '1':
if(p_game_info->board[0][1]==SPACE){
p_game_info->board[0][1]=X_SYMBOL;
}
break;
case '2':
if(p_game_info->board[0][2]==SPACE){
p_game_info->board[0][2]=X_SYMBOL;
}
break;
case '3':
if(p_game_info->board[1][0]==SPACE){
p_game_info->board[1][0]=X_SYMBOL;
}
break;
case '4':
if(p_game_info->board[1][1]==SPACE){
p_game_info->board[1][1]=X_SYMBOL;
}
break;
case '5':
if(p_game_info->board[1][2]==SPACE){
p_game_info->board[1][2]=X_SYMBOL;
}
break;
case '6':
if(p_game_info->board[2][0]==SPACE){
p_game_info->board[2][0]=X_SYMBOL;
}
break;
case '7':
if(p_game_info->board[2][1]==SPACE){
p_game_info->board[2][1]=X_SYMBOL;
}
break;
case '8':
if(p_game_info->board[2][1]==SPACE){
p_game_info->board[2][1]=X_SYMBOL;
}
break;
default:
;
}p_game_info->status=P2_TURN
}
else if (p_game_info->status=P2_TURN){
printf("enter number for 'O' from 0-8\n");
char ckey = (char) getchar();
switch (ckey){
case '0':
if(p_game_info->board[0][0]==SPACE){
p_game_info->board[0][0]=O_SYMBOL;
}
break;
case '1':
if(p_game_info->board[0][1]==SPACE){
p_game_info->board[0][1]=O_SYMBOL;
}
break;
case '2':
if(p_game_info->board[0][2]==SPACE){
p_game_info->board[0][2]=O_SYMBOL;
}
break;
case '3':
if(p_game_info->board[1][0]==SPACE){
p_game_info->board[1][0]=O_SYMBOL;
}
break;
case '4':
if(p_game_info->board[1][1]==SPACE){
p_game_info->board[1][1]=O_SYMBOL;
}
break;
case '5':
if(p_game_info->board[1][2]==SPACE){
p_game_info->board[1][2]=O_SYMBOL;
}
break;
case '6':
if(p_game_info->board[2][0]==SPACE){
p_game_info->board[2][0]=O_SYMBOL;
}
break;
case '7':
if(p_game_info->board[2][1]==SPACE){
p_game_info->board[2][1]=O_SYMBOL;
}
break;
case '8':
if(p_game_info->board[2][1]==SPACE){
p_game_info->board[2][1]=O_SYMBOL;
}
break;
default:
;
}}
}
void finished_game(struct game* p_game_info){
if((p_game_info->board[0][0]==O_SYMBOL)&&(p_game_info->board[0] [1]==O_SYMBOL)&&(p_game_info->board[0][2]==O_SYMBOL)||
(p_game_info->board[1][0]==O_SYMBOL)&&(p_game_info->board[1][1]==O_SYMBOL)&& (p_game_info->board[1][2]==O_SYMBOL)||
(p_game_info->board[2][0]==O_SYMBOL)&&(p_game_info->board[2][1]==O_SYMBOL)&&(p_game_info->board[2][2]==O_SYMBOL)||
(p_game_info->board[0][0]==O_SYMBOL)&&(p_game_info->board[1][0]==O_SYMBOL)&&(p_game_info->board[2][0]==O_SYMBOL)||
(p_game_info->board[0][1]==O_SYMBOL)&&(p_game_info->board[1][1]==O_SYMBOL)&&(p_game_info->board[2][1]==O_SYMBOL)||
(p_game_info->board[0][2]==O_SYMBOL)&&(p_game_info->board[1][2]==O_SYMBOL)&&(p_game_info->board[2][2]==O_SYMBOL)||
(p_game_info->board[0][0]==O_SYMBOL)&&(p_game_info->board[1][1]==O_SYMBOL)&&(p_game_info->board[2][2]==O_SYMBOL)||
(p_game_info->board[0][2]==O_SYMBOL)&&(p_game_info->board[1][1]==O_SYMBOL)&&(p_game_info->board[2][0]==O_SYMBOL))
{
p_game_info->status=P2_WON;
return;
}
else if((p_game_info->board[0][0]==X_SYMBOL)&&(p_game_info->board[0][1]==X_SYMBOL)&&(p_game_info->board[0][2]==X_SYMBOL)||
(p_game_info->board[1][0]==X_SYMBOL)&&(p_game_info->board[1][1]==X_SYMBOL)&&(p_game_info->board[1][2]==X_SYMBOL)||
(p_game_info->board[2][0]==X_SYMBOL)&&(p_game_info->board[2][1]==X_SYMBOL)&&(p_game_info->board[2][2]==X_SYMBOL)||
(p_game_info->board[0][0]==X_SYMBOL)&&(p_game_info->board[1][0]==X_SYMBOL)&&(p_game_info->board[2][0]==X_SYMBOL)||
(p_game_info->board[0][1]==X_SYMBOL)&&(p_game_info->board[1][1]==X_SYMBOL)&&(p_game_info->board[2][1]==X_SYMBOL)||
(p_game_info->board[0][2]==X_SYMBOL)&&(p_game_info->board[1][2]==X_SYMBOL)&&(p_game_info->board[2][2]==X_SYMBOL)||
(p_game_info->board[0][0]==X_SYMBOL)&&(p_game_info->board[1][1]==X_SYMBOL)&&(p_game_info->board[2][2]==X_SYMBOL)||
(p_game_info->board[0][2]==X_SYMBOL)&&(p_game_info->board[1][1]==X_SYMBOL)&&(p_game_info->board[2][0]==X_SYMBOL))
{
p_game_info->status=P1_WON;
return;
}
else
{
p_game_info->status=DRAW;
return;
}
}
game.h
#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
#define MAX_NAME_LEN 50
enum Bool { False, True };
enum status { P1_TURN, P2_TURN, P1_WON, P2_WON, DRAW };
typedef enum Bool boolean;
static const char SPACE= '-';
static const char X_SYMBOL = 'X';
static const char O_SYMBOL = 'O';
struct game {
char board[3][3];
char playerNames[2][MAX_NAME_LEN];
int status;
boolean finished;
};
void play_game();
void initialise_game(struct game* p_game_info, char* name1, char* name2);
void draw_banner();
void display_board( char board[3][3]);
void print_status (struct game*p_game_info );
void display_board_positions ();
void process_move(struct game* p_game_info);
void finished_game(struct game* p_game_info);
#endif // game
Current output
---------------
0 | 1 | 2
3 | 4 | 5
6 | 7 | 8
GAME STATUS
enter number for 'O' from 0-8
2
- | - | O
- | - | -
- | - | -
Process returned 0 (0x0) execution time : 7.731 s
Press any key to continue.
Your question is indeed chaotic. I'm not sure what you really want to know, but notice that 'else if (p_game_info->status=P2_TURN){' is wrong. You need a double equal sign there.

C error C2660: 'Menu' : function does not take 3 arguments

I am new to programming and do not understand this error.
I have the same arguments in the Menu () function and when I call the same function in the menu_principal () function.
In function menu_principal(), I want execute the switch-case statement by the function Menu() with 'option' variable.
Can you help please?
int main()
{
void menu_principal();
return 0;
}
void menu_principal()
{
bool stop = true;
int option;
const char *title = "MENU PRINCIPAL";
const char *options_menu[] = { "ARTIGOS", "CLIENTES", "ORCAMENTOS", "SAIR" };
int n_options = 4;
do
{
option = Menu(title, options_menu, n_options);
switch (option)
{
case 1:
Menu_Item();
break;
case 2:
Menu_Client();
break;
case 3:
Menu_Billing();
break;
case 4:
stop = false;
break;
}
} while (stop);
}
int Menu(const char *title1, const char *options_menu1[], int n_options1)
{
int OptionSelected= 1;
int key;
bool stop = true;
do
{
system("cls");
gotoxy(5, 3 + OptionSelected); printf(">>");
gotoxy(15, 2); printf("%s", title1);
for (int i = 0; i < n_options1; i++)
{
gotoxy(10, 4 + i);
printf("%s ", options_menu1[i]);
}
do
{
key = _getch();
} while (key != KEY_UP && key != KEY_DOWN && key != KEY_ENTER );
switch (key)
{
case KEY_UP:
OptionSelected--;
if (OptionSelected < 1)
{
OptionSelected = n_options1;
}
break;
case KEY_DOWN:
OptionSelected--;
if (OptionSelected > n_options1)
{
OptionSelected = 1;
}
break;
case KEY_ENTER:
stop = false;
break;
}
} while (stop);
return OptionSelected;
}
The compiler reads your program top to bottom, so it sees:
option = Menu(title, options_menu, n_options);
On this line, you call a previously unknown function, Menu.
Because the function is unknown, the compiler assumes it will be int Menu(void). (takes no parameters, returns an int).
That assumption is obviously different from how Menu eventually gets declared.
To fix this, declare the function properly near the top of your file:
int Menu(const char *title1, const char *options_menu1[], int n_options1);
Then, when the compiler encounters your function-call, it will not assume a declaration, it will use the declaration you already provided (takes 3 parameters, and returns an int)

Tic Tac Toe - Turns C

I've been turning around and around trying to figure out how to give my players turns. The questions is for there to be two players playing tic tac toe but I can't figure how to do that. Here's my code:
#include <stdio.h>
#include <stdlib.h>
void displayBoard(char [3][3]);enter code here
int playerType (int player, char boardArray[3][3]);
int selectLocation(char [3][3], int , int );
char setTurn(char [3][3], int , int , char );
int main()
{
int player,location;
char position;
char boardArray[3][3]={{'1','2','3'},
{'4','5','6'},
{'7','8','9'}};
player= playerType (player, boardArray);
int i;
for(i=0;i<9;i++)
{
if (player==3)
break;
else{
location=selectLocation(boardArray, player, location);
position=setTurn(boardArray, location, player, position);
}
}
return 0;
}
void displayBoard(char boardArray [3][3]) //This displays the tic tac toe board
{
printf("\t%c|%c|%c\n", boardArray[0][0], boardArray[0][1], boardArray[0][2]);
printf("\t%c|%c|%c\n", boardArray[1][0], boardArray[1][1], boardArray[1][2]);
printf("\t%c|%c|%c\n", boardArray[2][0], boardArray[2][1], boardArray[2][2]);
}
int playerType (int player, char boardArray [3][3]) //This decides who plays first
{
player=0;
printf("Enter 1 for Player X.\n");
printf("Enter 2 for Player O.\n");
printf("Enter 3 to Quit. \n");
scanf("%d", &player);
if (player == 1)
{
printf("You're player X.\n");
displayBoard(boardArray);
}
else if (player == 2)
{
printf("You're player O.\n");
displayBoard(boardArray);
}
else if(player == 3)
printf("You Quit.\n");
else
printf("Invalid Entry.\n");
return player;
}
int selectLocation(char boardArray[3][3], int player, int location) //This takes in the location
{
printf("Pick a location from 1-9.\n");
scanf("%d", &location);
return location;
}
char setTurn(char boardArray[3][3], int location, int player, char position) //This outputs the location
{
if (player == 1)
{
switch(location)
{
case 1:
{
boardArray[0][0]='x';
break;
}
case 2:
{
boardArray[0][1]='x';
break;
}
case 3:
{
boardArray[0][2]='x';
break;
}
case 4:
{
boardArray[1][0]='x';
break;
}
case 5:
{
boardArray[1][1]='x';
break;
}
case 6:
{
boardArray[1][2]='x';
break;
}
case 7:
{
boardArray[2][0]='x';
break;
}
case 8:
{
boardArray[2][1]='x';
break;
}
case 9:
{
boardArray[2][2]='x';
break;
}
default:
printf("invalid");
}
}
else if (player == 2)
{
switch(location)
{
case 1:
{
boardArray[0][0]='O';
break;
}
case 2:
{
boardArray[0][1]='O';
break;
}
case 3:
{
boardArray[0][2]='O';
break;
}
case 4:
{
boardArray[1][0]='O';
break;
}
case 5:
{
boardArray[1][1]='O';
break;
}
case 6:
{
boardArray[1][2]='O';
break;
}
case 7:
{
boardArray[2][0]='O';
break;
}
case 8:
{
boardArray[2][1]='O';
break;
}
case 9:
{
boardArray[2][2]='O';
break;
}
default:
printf("Invalid");
}
}
printf("\t%c|%c|%c\n", boardArray[0][0], boardArray[0][1], boardArray[0][2]);
printf("\t%c|%c|%c\n", boardArray[1][0], boardArray[1][1], boardArray[1][2]);
printf("\t%c|%c|%c\n", boardArray[2][0], boardArray[2][1], boardArray[2][2]);
return position;
}
Change player selection part player= playerType (player, boardArray); inside for loop like this -
int player,location;
char position;
char boardArray[3][3]={{'1','2','3'},
{'4','5','6'},
{'7','8','9'}};
int i;
for(i=0;i<9;i++)
{
player= playerType (player, boardArray);
if (player==3)
break;
else
{
location=selectLocation(boardArray, player, location);
position=setTurn(boardArray, location, player, position);
}
}

Evaluate postfix notation

I was doing my exercise but i stucked at the last step.
I have to evaluate postfix notation using stacks in C.
Code:
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct
{
int info;
}tipElement;
typedef struct
{
tipElement magacin [MAX];
int vrv;
}tipMagacin;
tipMagacin postfixStack;
void Inicijalizacija(tipMagacin *Mag)
{
(*Mag).vrv = -1; //warehouse is empty
}
int Prazen(tipMagacin Mag)
{
return(Mag.vrv == -1); //returns true if the warehouse is empty
}
int Poln(tipMagacin Mag)
{
return(Mag.vrv == MAX-1); //returns true if the warehouse is full
}
void Push(tipMagacin *Mag, tipElement Element)
{
if (Poln(*Mag)) printf("Warehouse is full\n"); //if it is full report an error
else
{
(*Mag).vrv++; //next position in the warehouse
(*Mag).magacin[(*Mag).vrv].info = Element.info; //put an element
}
}
void Pop(tipMagacin *Mag, tipElement *Element)
{
if (Prazen(*Mag)) printf("Warehouse is empty\n"); //if it is empty report an error
else
{
(*Element).info = (*Mag).magacin[(*Mag).vrv].info; //read the last element
(*Mag).vrv--; // delete it
}
}
int evaluate(int op1, int op2, char operate) {
switch (operate) {
case '*': return op2 * op1;
case '/': return op2 / op1;
case '+': return op2 + op1;
case '-': return op2 - op1;
default : return 0;
}
}
int evaluatePostfix (char *izraz, int n)
{
tipMagacin *Mag;
tipElement element;
tipElement go,z;
int i=0;
int op2;
char ch;
int value;
while (i < n) {
element.info = izraz[i];
if(isdigit(element.info))
{
Push(&postfixStack, element);
}
else
{
z=Pop(&postfixStack, &go);
op2=1;
value = evaluate(z,op2,ch);
Push(Mag,value);
}
i++;
}
return value;
}
my code works fine until here:
else
{
op1=Pop(&postfixStack, &go);
op2=Pop(&postfixStack, &go);
value = evaluate(op1,op2,element.info);
Push(&postfixStack, value);
}
i++;
}
return value;
}
the problem is: error: void value not ignored as it ought to be
my Push and Pop functions are void and i need to put the value that I remove from my stack to some int variable then i calculate them. put it doesnt put it for some reason i dont know.
Anyone help ?

Resources