code-tutorial.com

The best resources for developers

As function arguments, passing multidimensional arrays in C. In C, passing multidimensional arrays are no longer used and can be used as function arguments (again in a code library) in C. The examples below illustrate this.

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

data** array;
//initialize
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
for(y=0;y<h;y++){
  //malloc the "x" dimension
  array[y] = malloc(sizeof(data) * w);

  //iterate over the "x" dimension
  for(x=0;x<w;x++){
    //malloc the string in the data structure
    array[y][x].mystring = malloc(50); //50 chars

    //initialize
    array[y][x].myint = 6;
    strcpy(array[y][x].mystring, "w00t");
  }
}
int whatsMyInt(data** arrayPtr, int x, int y){
  return arrayPtr[y][x].myint;
}
printf("My int is %d.
", whatsMyInt(array, 2, 4));
My int is 6.

Tags: c function multidimensional-array

Source: By David as answer to the question

This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 4.0


Related code-snippets: