Putting [][] in **

c, c++

Solution

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)

Problem

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!

Original source

Related problems