Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multidimensional array by reference in C

Tags:

c

pointers

#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]) {
like image 980
tandem Avatar asked Feb 11 '23 07:02

tandem


2 Answers

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);
like image 181
David Ranieri Avatar answered Feb 24 '23 01:02

David Ranieri


void f(int *app[][20])

should be

void f(int app[][20])

and the call should be like

f(app);

The changes done in the function f() is visible in main() You can access the array in function f() like app[i][j]

like image 43
Gopi Avatar answered Feb 24 '23 02:02

Gopi