cpointers

Passing multidimensional array by reference in C


#include <stdio.h>

void f(int *app[][20]) {
    int i, j;
    for (i =0; i< 20; i++){
        for (j=0; j<20; j++){
            *app[i][j] = i;
        }
    }
}

int main() {
  int app[20][20];
  int i, j;
  f(&app);
    for (i =0; i< 20; i++){
        for (j=0; j<20; j++){
            printf("i %d, j%d  val= %d\n", i, j, app[i][j]);
        }
    }

  return 0;
}

What exactly am I doing wrong here? I don't get any error, but there is a segmentation fault and I don't know why.

te.c:15:5: warning: passing argument 1 of ‘f’ from incompatible pointer type
   f(&app);
     ^
te.c:3:6: note: expected ‘int * (*)[20]’ but argument is of type ‘int (*)[20][20]’
 void f(int *app[][20]) {

Solution

  • void f(int *app[][20]) { /* a 2d array of pointers to int */
    

    should be

    void f(int app[][20]) { /* a pointer to an array of 20 int's */
    

    or

    void f(int (*app)[20]) { /* a pointer to an array of 20 int's */
    

    *app[i][j] = i;
    

    should be

    app[i][j] = i; /* you don't need to dereference */
    

    f(&app);
    

    should be

    f(app);