# Thread: problem with pointers and bidimensional arrays

1. ## problem with pointers and bidimensional arrays

Hi all.

I have a problem with a pointer and a bidimensional array.
here's the code:

Code:
```includes..

typedef char t_board[5][4];
int i,j;

t_board *copy (t_board b) {
t_board *ptr;

ptr = (t_board *) malloc (sizeof(t_board));
for (i=0; i<5; i++)
for (j=0; j<4; j++)
*ptr[i][j] = b[i][j];

return ptr;
}

int main () {
t_board some_board, *new_board;

new_board = copy(some_board);
.
.
code here
.
.
}```
........

After this, I print new_board, and its ok; but the following code after
the call to copy, crashes. Don't know why.
if I remove the statment new_board = copy(some_board); , the code that follows runs ok.
Can someone tell me why?
Thanks;

2. > *ptr[i][j] = b[i][j];
You have to watch the precedence here.
You have a pointer to an array, not an array of pointers.

So you need
(*ptr)[i][j] = b[i][j];

3. ## it still not working

Originally Posted by Salem
> *ptr[i][j] = b[i][j];
You have to watch the precedence here.
You have a pointer to an array, not an array of pointers.

So you need
(*ptr)[i][j] = b[i][j];

the only difference between the code I posted, and the one i'm writting, is that some_board is now a parameter of a function.
I think it shouldn't be a mistake.

Code:
```void func(t_board b) {
t_board *new board;

new_board = copy(b);
}```

4. Interesting.... do go on.
Code:
```#include<stdio.h>
#include<stdlib.h>
typedef char t_board[5][4];

t_board *copy (t_board b) {
int i, j;
t_board *ptr;

ptr = malloc (sizeof(*ptr));
for (i=0; i<5; i++)
for (j=0; j<4; j++)
(*ptr)[i][j] = b[i][j];

return ptr;
}

int main () {
int i,j;
t_board some_board = {
{ 1, 2, 3, 4 },
{ 11, 12, 13, 14 },
{ 21, 22, 23, 24 },
{ 31, 32, 33, 34 },
{ 41, 42, 43, 44 },
};
t_board *new_board;

new_board = copy(some_board);
for ( i = 0 ; i < 5 ; i++ ) {
for ( j = 0 ; j < 4 ; j++ ) {
printf("%2d ", some_board[i][j] );
}
printf("\n");
}
for ( i = 0 ; i < 5 ; i++ ) {
for ( j = 0 ; j < 4 ; j++ ) {
printf("%2d ", (*new_board)[i][j] );
}
printf("\n");
}
free(new_board);
return 0;
}

\$ gcc -Wall bar.c
\$ ./a.out
1  2  3  4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
1  2  3  4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44```

5. Originally Posted by Gustaff
I think it shouldn't be a mistake.
Unfortunately, the C standard (by virtue of the precedence of operators) disagrees with you.

In a dispute between your expectations and behaviour of your compiler, the compiler almost always prevails. When the dispute is because your expectations differ from the standard, then there is almost 100% chance of your compiler prevailing.

Salem has pointed you in the right direction.

Popular pages Recent additions