tags:

views:

84

answers:

2

Hi,

I have a function, which is called sometimes with regular, sometimes dynamic arrays.

If I define the function as

function_name(int[10][10] a)

and send int** as a parameter, I get a warning. Opposite, if I declare

function_name(int** a)

and send int[][] as a parameter (after casting) I cannot access to array elements inside function.

What is the correctest way?

A: 

int ** and int [][] are not the same. The former is pointer to pointer to int whereas second one is 2-d array of int.

int[][] decays to int (*)[] when you pass it as argument to function.

void func(int arr[][10]) { //decays to `int (*arr)[10]` 
  printf("%d correct", arr[1][9]); //10th element of 2nd row
  //printf("%d correct", (*(arr + 1))[9]); //same as above
}

int main() {
  int (*arr)[10]; //pointer to array of ints
  arr = malloc(sizeof(int (*)[]) * 2); //2 rows & malloc will do implicit cast.

  arr[1][9] = 19;
  func(arr);

  return 0;
}
N 1.1
+1  A: 
Alok