-1

given the following code:

void myfunc(int** a){
   int temp=a[0][0];

}

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

i'm trying to pass 2D array test as a int** to myfunc, but my program crash. (I have read some code example using sth like a[][] as paramater, but what if I do want to use int**, then how should I do to access the 2D array in my function?

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
Ziqi Liu
  • 2,931
  • 5
  • 31
  • 64
  • 2
    [An array of arrays is not the same as a pointer to a pointer](https://stackoverflow.com/questions/18440205/casting-void-to-2d-array-of-int-c/18440456#18440456). – Some programmer dude Jul 30 '17 at 17:49
  • You cannot pass arrays to/from functions. But you can pass a pointer to an array. And as @Someprogrammerdude wrote: this is not a 2D array, nor a pointer to one. – too honest for this site Jul 30 '17 at 17:56

1 Answers1

1

C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:

1.Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.

void func(int** array, int rows, int cols)
    {
      int i, j;

      for (i=0; i<rows; i++)
      {
        for (j=0; j<cols; j++)
        {
          array[i][j] = i*j;
        }
      }
    }

    int main()
    {
      int rows, cols, i;
      int **x;

      /* obtain values for rows & cols */

      /* allocate the array */
      x = malloc(rows * sizeof *x);
      for (i=0; i<rows; i++)
      {
        x[i] = malloc(cols * sizeof *x[i]);
      }

      /* use the array */
      func(x, rows, cols);

      /* deallocate the array */
      for (i=0; i<rows; i++)
      {
        free(x[i]);
      }
      free(x);
    }


2.When both dimensions are available globally (either as a macro or as a global constant).

#include <stdio.h>
const int M = 3;
const int N = 3;

void print(int arr[M][N])
{
    int i, j;
    for (i = 0; i < M; i++)
      for (j = 0; j < N; j++)
        printf("%d ", arr[i][j]);
}

int main()
{
    int arr[][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    print(arr);
    return 0;
}
Himanshu Ray
  • 38
  • 1
  • 12