2

I have the following code in the caller function

int matrix[3][3] = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};
find_index(matrix);

and the find_index's prototype is:

void find_index(int** m);

and I got compiler error: cannot convert 'int (* )[3]' to ‘int**’

Anyway I can fix this? Thanks!

update:

is there a way that I can then use m[a][b] operator in the second function instead of passing the column number and do m[a * col_num + b]?

2
  • 1
    where in matrix is an array of pointers? Of course they are not compatible types... Commented Dec 2, 2011 at 0:08
  • 1
    @tenfour the confusion obviously comes from the fact that you can pass an int[] to a function expecting an int*, but not an int[][] to a function expecting an int**. Commented Dec 2, 2011 at 0:10

2 Answers 2

6

A double indexed array still just corresponds to a single pointer, not a pointer to a pointer.

Sign up to request clarification or add additional context in comments.

3 Comments

is there a way that I can then use m[a][b] operator in the second function instead of passing the column number and do m[a * col_num + b]? Thanks!
if you really want to use m[a][b] inside the function, you can declare it as find_index(int m[][3])
you definitely don't need to pass column number. if you pass the array as int*, then you just need to understand how the columns/rows are laid out linearly. so if you pass an int* m, you would find m[0] = 1, m[3] = 4, m[6] = 7, etc. The memory is laid out linearly with each row following the previous
4

In memory, an int** looks like

[0] ----> [0] ---> int
          [1] ---> int
          [2] ---> int

[1] ----> [0] ---> int
          [1] ---> int
          [2] ---> int

[2] ----> [0] ---> int
          [1] ---> int
          [2] ---> int

But an int[][] looks like

[0][1][2][0][1][2][0][1][2]
(0)      (1)      (2)

So you can see how indexing them would cause different things to happen (one dereferences pointers, one performs the arithmetic differently), and they are not compatible. Trying to index an int[][] like an int** would cause one of the integers you are storing to be dereferenced, causing Undefined Behaviour.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.