Rogue
Rogue

Reputation: 779

Edit a 2D array through a function in C

I have this function : void foo( char tab[8][8] )

I want this function to edit the values of the tab array, so i tried theses syntax :

void foo( char *(*tab)[8][8] )
void foo( char *(tab)[8][8] )
void foo( char **tab )

And a LOT of others. I always get a fail while compiling, like this one : error: cannot convert 'char ()[8][8]' to 'char (*)[8][8]' for argument '1' (...)

So, my quesiton is : how to create and pass to a function a pointer to a 2D array ?

Thanks.

Upvotes: 3

Views: 3453

Answers (2)

haccks
haccks

Reputation: 106012

This time try to declare your function as

void foo( char (*tab)[8] );  

and call it as

foo(point);  

Note that in this case you need to pass only array name as it decays to pointer when passed to a function (some exceptions are there). After decay it is of type char (*)[8].

You can do it also by declaring

void foo( char (*tab)[8][8] ); 

and call it as

foo(&point); 

In this case notice that I passed &poinnt, i.e, address of the entire array which is of type char (*)[8][8].
Sample:

void foo(char (*tab)[8][8])
{    
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 68j++)
        {
              scanf("%d", &(*tab)[i][j]);
        }
    }
}

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 753870

With an array, you can always modify the data in the function because what is passed is a pointer (in the absence of const qualifiers, of course). That is, you could write:

void foo(char tab[8][8])
{
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
            tab[i][j] = (x + y) % 2 : 'X' : 'O';
    }
}

And call it:

void calling_func(void)
{
    char board[8][8];
    foo(board);
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
            putchar(tab[i][j]);
        putchar('\n');
    }
}

You can get the error messages you were seeing if you write:

   foo(&board);

That passes a pointer to an array to the function. For that to work, you have to rewrite the function as:

void foo(char (*tab)[8][8])
{
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
            (*tab)[i][j] = (x + y) % 2 : 'X' : 'O';
    }
}

However, this is seldom the correct way to write the code. Use the first alternative until this is forced upon you (which probably won't be this year — I don't recall having to use a pointer to an array except to answer questions on SO, but maybe it was such a ghastly experience that I have forgotten all about it).

Upvotes: 1

Related Questions