Possible Duplicate:
Passing two-dimensional array via pointer
int table[20][20];
int** table1 = table;
int a;
table[0][0] = 4;
a = table1[0][0];
the last line gives me Access violation, and i dont get it ..
thanks in advance!
Possible Duplicate:
Passing two-dimensional array via pointer
int table[20][20];
int** table1 = table;
int a;
table[0][0] = 4;
a = table1[0][0];
the last line gives me Access violation, and i dont get it ..
thanks in advance!
The short answer is that a pointer to a pointer is not the same as an array of arrays.
You can't make a int ** from a two dimensional int array in one assignment. First, you need to allocate the correct number of pointers: table1 = malloc(sizeof(int*) * 20);
Then you can use a loop to fill in your next level pointers:
for(int i = 0; i < 20; i++)
table1[i] = table[i];
The reason is that pointer to pointer is ONE memory location that holds an address. When you make the first allocation, that makes that pointer point to 20 int pointers. We then assign each of those pointers the first address of each row in the original table. Now, when we use a = table1[0][0]
, the compiler will go fetch table1[0] - so the first pointer in the array we set up in the loop. This points to table[0] row, so we fetch the [0] element from that, and get the 4 that was stuffed in there [of course, any other number index would also get four, so it's hard to show that it works right in this case).
In the table[y][x]
case, the compiler will take the address of table, add y * 20 * sizeof(int) to it, and then add x * sizeof(int). Which gives us a nice place in the "square" lump of memory that "table" is.
(Again, typing too much, two more answers since I started writing this)
C compilers are just too forgiving:
int** table1 = table;
c.c: In function ‘main’: c.c:3:17: warning: initialization from incompatible pointer type [enabled by default]
If we feed it incorrect code, the compiler complains, and we ignore the complaint and then get some strange outcome, should we wonder?
Anyway, table1 doesn't point to a pointer to int, and the way it's going to crash is a matter of implementation (alignment, segmentation etc.)
Although table1[1]
is of type pointer, there are no pointers anywhere in table
.
Given
int table[20][20];
table
is compatible with int*
, not int**
.
This should compile and be able to access table1
from table1[0]
to table1[399]
:
int* table1 = table;
Ask yourself: Given a pointer, and being told to access item 3, 4 - how should the compiler know how large the first dimension of your two-dimensional array is, in order to skip the right amount of items?
Correct: Not at all.