Using functions with pointer arguments - Connect 4

This is a discussion on Using functions with pointer arguments - Connect 4 within the C Programming forums, part of the General Programming Boards category; Hi all, I just started programming in C (I've learnt Java and Python), and this concept of pointers is driving ...

  1. #1
    Registered User
    Join Date
    Sep 2012
    Posts
    8

    Using functions with pointer arguments - Connect 4

    Hi all,
    I just started programming in C (I've learnt Java and Python), and this concept of pointers is driving me crazy. I know that basis of pointers, but when applying to a more complicated problem, it's really confusing. I was assigned a Connect 4 homework in which I have to use a single char array to represent the board game (6x7). There are a tons of suggested functions in the requirements (to help us work on the project), but most of them use pointers as function arguments and I've been struggling trying to figure out how they work.
    I know this is nothing, but here is what I have so far:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <string.h>
    #define RED 1;
    #define BLACK 2;
    
    
    static const int NUM_ROWS = 6;
    static const int NUM_COLS = 7;
    
    
    
    
    void menu() {
        printf("Welcome to the game connect 4 \n");
        printf("Please choose whether you want to be Red or Black below... \n");
    }
    
    
    // returning the position on the array, given the position of the board
    int position(int row, int col) {
        int pos;
        pos = (row*7) + col;
        return pos;
    }
    
    
    void printBoard(char *grid) {
        
    }
    main() {
        char grid[NUM_ROWS*NUM_COLS];
        int i;
        printBoard(grid);
    }
    I'm working on getting void printBoard(char *grid) to print out the board, and with the char pointer as its argument, I really have no clue. Here is what the specs say for this function:

    Code:
     void printBoard(char *grid);
       // pre: grid is a valid connect-four board array
    // post: the board grid is printed to the screen
    I've been reading about pointers yesterday. Any help of hints would be greatly appreciated. Thanks in advance everyone !

  2. #2
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    If it helps, in this case, you can think of the pointer as an array and use standard array indexing notation to access the elements through the pointer

    Code:
    void printBoard(char *grid) {
        printf("%c%c%c%c%c%c\n", grid[0], grid[1], grid[2], grid[3], grid[4], grid[5]);
    }
    But keep in mind that arrays are not pointers and pointers are not arrays!

    I suggest you read the comp.lang.c FAQ particularly section 6.

  3. #3
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Welcome to the forum

    This
    Code:
    char grid[NUM_ROWS*NUM_COLS];
    declares an one dimension array with size NUM_ROWS*NUM_COLS.
    If you wish to declare a 2-dimensional array you should write something like this
    Code:
    char grid[NUM_ROWS][NUM_COLS];
    Then in Java the arrays now their length,so you use the length function to get their length immediately .In C,it is programmer's responsibility to keep track of the size of the array.

    When we want to go through a 2 - dimensional array we use a double for loop to achieve this

    Here is an example
    Code:
    char array[rows][col];
    int i,j;
    
    for(i=0 ; i < rows ; i++)
    {
          for( j = 0 ; j < col ; j++)
          {
                  array[i][j]='a';
           }
    }
    
    /*now the array is filled up by the char a*/
    
    for(i=0 ; i < rows ; i++)
    {
          for( j = 0 ; j < col ; j++)
          {
                /*Now we are going to print every single cell of array.
                First we are going through the first row,then the second,and so on*/
                  printf("At cell %d %d , %c is stored",i,j,array[i][j]);
           }
           printf("\n");
    }
    So in the printBoard function i would do something like this

    Notice that you do not need to pass as parameters the dimensions of the array because they are declared as global variables.I would suggest you to avoid this style of global variables,because in large programs,there is a good chance these variables cause problems
    So i would suggest you to declare them in main and pass them in the function as parameters,or define them,as you did with black and red

  4. #4
    Registered User
    Join Date
    Sep 2012
    Posts
    8
    Thank you so much for the replies everyone !
    @std10093: For this project I have to use a single array of length 42 to represents the board game ( I think this complicates things quite a bit ), that's why I have the function position that convert the format [row, col] to char[index]

  5. #5
    Registered User
    Join Date
    Sep 2012
    Posts
    8
    Quote Originally Posted by qny View Post
    If it helps, in this case, you can think of the pointer as an array and use standard array indexing notation to access the elements through the pointer

    Code:
    void printBoard(char *grid) {
        printf("%c%c%c%c%c%c\n", grid[0], grid[1], grid[2], grid[3], grid[4], grid[5]);
    }
    But keep in mind that arrays are not pointers and pointers are not arrays!

    I suggest you read the comp.lang.c FAQ particularly section 6.
    Thank you qny. I've tried it but it doesn't properly report the size of the actual grid
    Code:
    void printBoard(char *grid) {
        int i;
        for (i = 0; i < sizeof(grid) ; i++)
            grid[i] = '-';
        printf("%c %c %c %c %c %c %c\n", 
        grid[0],grid[1],grid[2],grid[3],grid[4],grid[5],grid[6]) ;
    }
    I tried this to print out the first 7 elements of the grid[42], and it only prints out:
    Code:
    ▒ j  a ▒ ▒ #
    I guess the problem lies within my for loop (sizeof(grid)).

    EDIT: Got it fixed !
    Last edited by Thinh Cao; 09-30-2012 at 10:14 AM.

  6. #6
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Quote Originally Posted by Thinh Cao View Post
    Thank you qny. I've tried it but it doesn't properly report the size of the actual grid
    The grid, inside the function, is not an array; it is a pointer. I told you you could think of the pointer as an array ... but for the sizeof operator you cannot. It's all explained in the comp.lang.c FAQ i linked to.

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Easy enough to print out a 1D array, as rows and columns:

    Code:
    #include <stdio.h>
    
    #define ROWS 4
    #define COLS 3
    
    void print(int *cube);
    
    int main(void) {
       int cube[]={1,2,3,4,5,6,7,8,9,10,11,12};
       
       print(cube);
       printf("\n");
       return 0;
    }
    
    void print(int *cube) {
       int sqr;  
       for(sqr=0;sqr<ROWS*COLS;sqr++) {
          if(sqr % COLS==0 && sqr)
             printf("\n");
          printf("%2d ",cube[sqr]);
       }
       printf("\n");
    }

  8. #8
    Registered User
    Join Date
    Sep 2012
    Posts
    8
    @Adak:
    Wow ! I tried it and it works flawlessly, but I don't really understand the part after the for loop in void print(). If you can elaborate it a bit, it would be great ! Thanks though.

    EDIT: So I'm working on the checkWin() function that check for winning combinations
    Code:
    int checkWin(char *grid) {
    	int i;
    	int j;
    	for (i = 0; i < NUM_ROWS; i++) {
    		for (j = 0; j < NUM_COLS; j++) {
    			if ( grid[pos(i,j)] == grid[pos(i,j+1)] == grid[pos(i,j+2)]== grid[pos(i,j+3)] == RED) {
    				return 1;
    			}
    		}
    	}
    }
    The number of row to i and column to j, and I'm checking for horizontal winning combination (since there are 7 columns, there will only be 4 winning combinations each row, which are from col 0 to col 3, 1 to 4, 2 to 5 and 3 to 4. Increment the number of row number after the winning combinations of a row is checked to check the whole board). I tried to compile this and it it gave me a compile error:
    Code:
    project1.c: In function `checkWin':
    project1.c:75: error: parse error before ';' token
    project1.c: At top level:
    project1.c:80: error: parse error before '}' token
    Any suggestions or hints would be appreciated. Thanks in advance guys!
    Last edited by Thinh Cao; 09-30-2012 at 12:40 PM.

  9. #9
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Hmmm ... you can't string conditions like this in C (this has an unexpected meaning)
    Code:
    if ( grid[pos(i,j)] == grid[pos(i,j+1)] == grid[pos(i,j+2)]== grid[pos(i,j+3)] == RED)
    You need to make each comparison alone (I've separated them into individual lines) by using the && (logical AND) operator
    Code:
    if ( grid[pos(i,j)] == grid[pos(i,j+1)]
      && grid[pos(i,j)] == grid[pos(i,j+2)]
      && grid[pos(i,j)] == grid[pos(i,j+3)]
      && grid[pos(i,j)] == RED)

  10. #10
    Registered User
    Join Date
    Sep 2012
    Posts
    8
    Quote Originally Posted by qny View Post
    Hmmm ... you can't string conditions like this in C (this has an unexpected meaning)
    Code:
    if ( grid[pos(i,j)] == grid[pos(i,j+1)] == grid[pos(i,j+2)]== grid[pos(i,j+3)] == RED)
    You need to make each comparison alone (I've separated them into individual lines) by using the && (logical AND) operator
    Code:
    if ( grid[pos(i,j)] == grid[pos(i,j+1)]
      && grid[pos(i,j)] == grid[pos(i,j+2)]
      && grid[pos(i,j)] == grid[pos(i,j+3)]
      && grid[pos(i,j)] == RED)
    Thank you qny for the reply, but it still prompts the same compiler error:
    Code:
    $ gcc project1.c -o project
    project1.c: In function `checkWin':
    project1.c:78: error: parse error before ';' token
    Here is the modified checkWin as you suggested:
    Code:
    int checkWin(char *grid) {
    	int i;
    	int j;
    	for (i = 0; i < NUM_ROWS; i++) {
    		for (j = 0; j < NUM_COLS; j++) 
    			if (grid[pos(i,j) == grid[pos(i,j+1)]
    				&& grid[pos(i,j) == grid[pos(i,j+2)]
    				&& grid[pos(i,j) == grid[pos(i,j+3)]
    				&& grid[pos(i,j) == RED)
    					return 1;
    			else 
    				return 0;
    	}
    }

  11. #11
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Does you have anything against the character ']' ?

    My code had 7 of those characters; your code has 3.
    4 of them "got lost" during the copy/paste operation

  12. #12
    Registered User
    Join Date
    Sep 2012
    Posts
    8
    I'm sorry I typed them to quickly and forgot. I just re-compiled after checking it again carefully, but the same error message still pops up
    Code:
    int checkWin(char *grid) {
    	int i;
    	int j;
    	for (i = 0; i < NUM_ROWS; i++) {
    		for (j = 0; j < NUM_COLS; j++) 
    			if (grid[pos(i,j)] == grid[pos(i,j+1)]
    				&& grid[pos(i,j)] == grid[pos(i,j+2)]
    				&& grid[pos(i,j)] == grid[pos(i,j+3)]
    				&& grid[pos(i,j)] == RED) {
    					return 1;
    					}
    			else 
    				return 0;
    	}
    }

  13. #13
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Quote Originally Posted by Thinh Cao View Post
    Code:
    #define RED 1;
    #define BLACK 2;
    Oops! I didn't notice this before.
    Do not put a semicolon at the end of macro definitions.
    They get substituted as a whole. For example, the 1st line below gets expanded to the 2nd before compilation
    Code:
                if (grid[pos(i,j)] == RED]
                if (grid[pos(i,j)] == 1;]
    Last edited by qny; 09-30-2012 at 01:47 PM.

  14. #14
    Registered User
    Join Date
    Sep 2012
    Posts
    8
    Quote Originally Posted by qny View Post
    Oops! I didn't notice this before.
    Do not put a semicolon at the end of macro definitions.
    They get substituted as a whole. For example, the 1st line below gets expanded to the 2nd before compilation
    Code:
                if (grid[pos(i,j)] == RED]
                if (grid[pos(i,j)] == 1;]
    Thank you so much for your help !!!
    btw if I changed the constant to a char, say I do:
    #define RED 'X'
    this is still correct and on the board, when I assigned an index to RED, it will appear on the screen at X right ?
    Thanks again qny, you have been really patient and helpful !!!

  15. #15
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Quote Originally Posted by Thinh Cao View Post
    Thank you so much for your help !!!
    You're welcome.

    Quote Originally Posted by Thinh Cao View Post
    btw if I changed the constant to a char, say I do:
    #define RED 'X'
    this is still correct and on the board, when I assigned an index to RED, it will appear on the screen at X right ?
    Yes, it is correct and works as you expect.

    Nitpick: the constant 'X' appears to be a char but is, in fact, an int (that's one of the differences between C and C++).
    You can continue to think of constants in the form 'X' as chars.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 01-29-2012, 09:20 AM
  2. Replies: 5
    Last Post: 07-28-2011, 07:45 AM
  3. Functions as arguments
    By jw232 in forum C++ Programming
    Replies: 2
    Last Post: 04-19-2008, 12:11 PM
  4. Please help connect file pointer
    By ralphwiggam in forum C Programming
    Replies: 10
    Last Post: 10-02-2006, 10:55 AM
  5. functions and pointer arguments
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 01-08-2002, 05:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21