Christopher Bell - 1 year ago 67
C Question

Pass variable in form int[][] into method with type int**

I have a two dimensional array of integers and a function that retrieves a particular column from that two dimensional array. The function has an int** as a parameter. How can I create a int** to point to my int[][].

``````int* getColumn(int **matrix, int rows, int column, int columnNum)
{
...
}

int main()
{
int mat[2][2];
mat[0][0] = 1;
mat[0][1] = 2;
mat[1][0] = 3;
mat[1][1] = 4;

getColumn( ? , 2, 2, 1);
}
``````

There's no easy way to do it, because those are completely different types - one is a 2D array, and the other is a pointer to (presumably a 1D array of) pointers to (presumably 1D arrays of) ints.

This is the memory layout of an `int[2][2]` at let's say address 5678: (and assuming ints are one byte, which they're not on most real systems, but let's pretend)

``````Address  5678 5679 5680 5681
+----+----+----+----+
| 1  | 2  | 3  | 4  |
+----+----+----+----+
``````

This is the memory layout of one possible `int**` representing the same array:

``````Address  2345 2346 ... 3456 3457 ... 5682
+----+----+...+----+----+...+----+----+
| 1  | 2  |...| 3  | 4  |...|2345|3456|
+----+----+...+----+----+...+----+----+
``````

As you can see, they're not the same. The main difference is that with the `int**` representation each row is allowed to be at a completely different address, and "the matrix" is actually an array holding a pointer to each row

However, you can make an array of pointers to each row yourself:

``````int *rows[2] = {
mat[0],
mat[1]
};
getColumn(rows, 2, 2, 1);
``````

but this gets complicated if your matrix isn't always the same size.

(The memory layout for this would be:

``````Address  5678 5679 5680 5681 ... 5700 5701
+----+----+----+----+...+----+----+
| 1  | 2  | 3  | 4  |...|5678|5680|
+----+----+----+----+...+----+----+