1

I'm writing a code to find the shortest path through a maze using djikstra's algorithm.

When I pass my array I'm getting the

warning "passing argument 1 of 'traverse' from incompatible pointer type" 
expected 'int (*)[(sizetype)(n)]' but argument is of type 'int **'

I had originally initialized and allocated my matrix in main here:

int **mat;
mat = (int **)malloc(sizeof(int *)*n);
for(i=0; i<n; i++){
  mat[i]=(int *)malloc(sizeof(int)*n);
}

And I'm creating a function by

void traverse(int mat[n][n], int src){

I then call this function in main here

traverse(mat, 0);

I'm sure it's a problem with passing an array as a pointer, but I'm not too familiar with the rules here. Any help is appreciated.

r2333
  • 103
  • 1
  • 4
  • 1
    Welcome to Stack Overflow! [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh May 10 '16 at 15:32
  • I'm going to read up on this now, thanks. – r2333 May 10 '16 at 15:35
  • 3
    As warning says: `void traverse(int mat[n][n], int src)` --> `void traverse(int **mat, int src)` – LPs May 10 '16 at 15:39
  • 1
    In case that comment didn't soundly amplify the problem, an array of arrays is *not* synonymous with an array of pointers. They are different beasts. – WhozCraig May 10 '16 at 15:40
  • That was it, thank you! – r2333 May 10 '16 at 15:41
  • @WhozCraig that makes more sense to me now, thanks. – r2333 May 10 '16 at 15:42
  • You also need to pass `n` to the `traverse()` method, or else it will not be able to determine the size of the matrix – FredK May 10 '16 at 15:59

1 Answers1

0

int **mat is a "pointer to pointer to int".

int mat[n][n], as a function parameter is a the same as int (*mat)[n] is a "pointer to array n of int".

The first points to a pointer, the seconds, points to an array -- not the same type.


Rather than pass mat to traverse(), as a int mat[n1][n2], pass as a int **. Also pass the 2 dimensions.

// void traverse(int mat[n1][n2], int src){
void traverse(int **mat, size_t n1, size_t n2, int src) {
...

--

Suggested allocation code change

int **mat;
size_t n1 = foo();
size_t n2 = foo();
mat = malloc(sizeof *mat * n1);
for(size_t i=0; i<n1; i++){
  mat[i]= malloc(sizeof *(mat[i]) * n2);
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256