Passing multidimensional arrays as function arguments in C

Tags: c
By : David

In C can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be ?

In addition my multidimensional array may contain types other than strings.

By : David


Pass an explicit pointer to the first element with the array dimensions as separate parameters. For example, to handle arbitrarily sized 2-d arrays of int:

void func_2d(int *p, size_t M, size_t N)
  size_t i, j;
  p[i*N+j] = ...;

which would be called as

int arr1[10][20];
int arr2[5][80];
func_2d(&arr1[0][0], 10, 20);
func_2d(&arr2[0][0], 5, 80);

Same principle applies for higher-dimension arrays:

func_3d(int *p, size_t X, size_t Y, size_t Z)
  size_t i, j, k;
  p[i*Y*Z+j*Z+k] = ...;
func_3d(&arr[0][0][0], 10, 20, 30);
By : John Bode

int matmax(int **p, int dim) // p- matrix , dim- dimension of the matrix 
    return p[0][0];  

int main()
   int *u[5]; // will be a 5x5 matrix

   for(int i = 0; i < 5; i++)
       u[i] = new int[5];

   u[0][0] = 1; // initialize u[0][0] - not mandatory

   // put data in u[][]

   printf("%d", matmax(u, 0)); //call to function
   getche(); // just to see the result
By : Pedro

You can do this with any data type. Simply make it a pointer-to-pointer:

typedef struct {
  int myint;
  char* mystring;
} data;

data** array;

But don't forget you still have to malloc the variable, and it does get a bit complex:

int x,y,w,h;
w = 10; //width of array
h = 20; //height of array

//malloc the 'y' dimension
array = malloc(sizeof(data*) * h);

//iterate over 'y' dimension
  //malloc the 'x' dimension
  array[y] = malloc(sizeof(data) * w);

  //iterate over the 'x' dimension
    //malloc the string in the data structure
    array[y][x].mystring = malloc(50); //50 chars

    array[y][x].myint = 6;
    strcpy(array[y][x].mystring, "w00t");

The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should check the return of malloc().)

Now let's say you want to pass this to a function. You can still use the double pointer, because you probably want to do manipulations on the data structure, not the pointer to pointers of data structures:

int whatsMyInt(data** arrayPtr, int x, int y){
  return arrayPtr[y][x].myint;

Call this function with:

printf("My int is %d.\n", whatsMyInt(array, 2, 4));


My int is 6.
By : andrewrk

This video can help you solving your question :)
By: admin