user1779598
user1779598

Reputation: 51

Passing a multi-dimensional array to a function in C

I wrote this function to swap values in a multi-dimensional array with my understanding that arrays are pointers.

void
swap(int* a, int* b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

However when I try to use the function

swap(board[d-1][d-2]), board[d-1][d-33];

I get these errors from the compiler and I don't know why:

fifteen.c: in function 'init':
fifteen.c:166:9: error: passing argument 1 of 'swap' makes pointer from integer without a cast [-werror]
fifteen.c:45:6: note: expected 'int *' but argument is of type 'int'
fifteen.c:166:9: error: passing argument 2 of 'swap' makes pointer from integer without a cast [-werror]
fifteen.c:45:6: note: expected 'int *' but argument is of type 'int'

How do I fix it?

Upvotes: 1

Views: 380

Answers (3)

dead programmer
dead programmer

Reputation: 4365

you are passing wrong argument

swap (board[d-1][d-2]), board[d-1][d-33]);

you have to pass the address of the variable actually.So the correct way of calling this function is below.

swap (&board[d-1][d-2]), &board[d-1][d-33]);

I think this will help you.

Upvotes: 0

md5
md5

Reputation: 23699

board[d-1][d-2] and board[d-1][d-33] are int. To swap the both, you have to pass their addresses:

swap (&board[d - 1][d - 2]), &board[d - 1][d - 33];

If you are using swap (board[d - 1][d - 2]), &board[d - 1][d - 33]), the instruction int tmp = *a; will try to access to the value on the address board[d - 1][d - 2]: this make no sense! Because you are using pointers, you have to pass the address of your variables.

Upvotes: 3

alk
alk

Reputation: 70911

You need to pass the addresses (swap() expects two int *):

swap (&board[d-1][d-2], &board[d-1][d-33]);

Upvotes: 2

Related Questions