
Beginner needs help with strings, pointers, arrays
: Help. This is my first semester programming in anything but dBase III+ (no
: snickering, I know it's not really programming).I'm trying to write a
: tic-tac-toe program and I'm confused by passing-by-reference. I want the
: user to input a char 1-9 that corresponds to a space on the ttt grid. Do I
: need to pass the string grid_input to the function? Or should I pass a
: pointer? When passing by reference, does the function need a return type,
: or does void function() work? I have included some code below. The error I
: receive when compiling is "warning: improper pointer/integer combination:
: arg #1.
: Thanks
: Cindy Katz
: #include <stdio.h>
: #include <stdlib.h>
: #include <string.h>
: void print_grid(char *ptr); /* prints tic-tac-toe board */
: int game_won(char gi[]); /* check to see if game is won */
: void player_1(char *ptr); /* player 1 move */
/* ### this prototype doesn't match the actual function; it should
be 'void player_1(char *, char *);'
*/
: void player_2(char *ptr); /* player 2 move */
: void main(int argc, char *argv[])
: {
: int num_games; /* number of games user wants to play */
: int won1=0, won2=0; /* number of games each player has won */
: int i; /* loop counter */
: char grid_input[10];
: char *ptr;
: more code here, then void player_1() is where the compile errors begin
: for (i=1; i<=num_games; i++)
: {
: grid_input[0] = '1';
: grid_input[1] = '2';
: grid_input[2] = '3';
: grid_input[3] = '4';
: grid_input[4] = '5';
: grid_input[5] = '6';
: grid_input[6] = '7';
: grid_input[7] = '8';
: grid_input[8] = '9';
: grid_input[9] = '\0';
/* ### 'strcpy(grid_input, "123456789");' would be easier */
: ptr = grid_input;
: if (i%2 == 1)
: { player_1(*ptr, grid_input);
/* ### this call doesn't match the actual function or the prototype;
it should be 'player_1(ptr, grid_input);'
*/
: more code
: void print_grid(char *ptr)
: {
: printf(" %c | %c | %c \n",*ptr, *(ptr+1), *(ptr+2));
: printf("---+---+---\n");
: printf(" %c | %c | %c \n",*(ptr+3), *(ptr+4), *(ptr+5));
: printf("---+---+---\n");
: printf(" %c | %c | %c \n",*(ptr+6), *(ptr+7), *(ptr+8));
: }
: still more code
: void player_1(char *ptr, char gi[])
: {
: char go1; /* player 1's move */
: print_grid(*ptr);
/* ### this call doesn't match the actual function parameters;
use 'print_grid(ptr);'
*/
: printf("Player 1, enter your go: ");
/* ### add 'fflush(stdout);' here */
: scanf("%c", go1);
/* ### scanf takes pointers - use 'scanf(" %c", &go1);' */
: fflush(stdin);
/* ### do not use fflush(stdin) */
: while ((ptr = strchr(gi,go1))== NULL)
: { printf("Invalid move. Please try again.\n");
: print_grid(*ptr);
/* ### see above */
: printf("Player 1, enter your go: ");
/* ### see above */
: scanf("%c", go1);
/* ### see above */
: fflush(stdin);
/* ### see above */
: }
: *ptr = 'X';
: }
Will