Pass a 2D char array to a function in C

17,160

Solution 1

You can just pass arrays as function arguments with definition of their size.

bool canReach(char board[ROWS][COLS], int i, int j);

When the size is unknown, pointers are the way.

bool canReach(char* board, int i, int j);

You should know, that arrays != pointers but pointers can storage the address of an array.

Solution 2

Here is a demonstrative program

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

bool canReach( int n, int m, char board[][m] )
{
    for ( int i = 0; i < n; i++ )
    {
        for ( int j = 0; j < m; j++ )
        {
            board[i][j] = 0;
        }
    }

    return printf( "Hello SaarthakSaxena" );
}    

int main( void )
{
    const int ROWS = 8;
    const int COLS = 8;

    char board[ROWS][COLS];

    canReach( ROWS, COLS, board );

    return EXIT_SUCCESS;
}

Its output is

Hello SaarthakSaxena
Share:
17,160
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm a beginning programmer who is confused with passing a two dimensional array to a function. I think it may just be a simple syntax problem. I've looked for an answer, but nothing I've found seems to help, or is too far above my level for me to understand.

    I identify the array and the function in the main function as, and after initializing it, attempt to call it:

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>
    
    int const ROWS = 8;
    int const COLS = 8;
    
    int main(int argc, char** argv) {
    
    char board[ROWS][COLS];
    
    bool canReach(char board[][], int i, int j);
    
    //initialize array
    
    //values of i and j given in a for loop
    
    canReach(board, i, j);
    
    return (EXIT_SUCCESS);
    }
    

    While writing the function outside the main function, I defined it exactly the same as I did in the main function.

    bool canReach(char board[][], int i, int j){
    //Functions purpose
    }
    

    When I attempt to build the program, I'm given this error twice and the program does not build:

    error: array has incomplete element type 'char[][]'
    bool canReach(char board[][], int i, int j)
                            ^
    

    Please note that I'm trying to pass the entire array to the function, and not just a single value. What can I do to fix this problem? I would appreciate it if it didn't have to use pointers, as I find them quite confusing. Also, I've tried to leave out things that I thought weren't important, but I may have missed something I needed, or kept in things I didn't. Thank you for your time in helping out this starting programmer!