Dmytro Osaulenko Dmytro Osaulenko - 6 days ago 5
C Question

Passing 2D int array from one function to another in c

For example, I have two functions: first one gets height and width from main() and reads 2D int array

int read_price (int height, int width) {
int i, j;
int array[height][width];

printf("Enter your values:\n");

for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
scanf("%d", &array[i][j]);
}
}
}


Second function gets values from the first and prints it.

void print_array () {
int i, j;
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
}


And - the question! How should I call second function inside the first (with which arguments)? And which arguments should I write beetween brackets in the name of second function.

I tried to call in this (and some another) way(s), but I get errors.

print_array (array[height][width]);

Answer

In C99 you can use array with a variable length. In your case the definition of the function print_array will look like:

void print_array (int height, int width, int array[height][width]) {
  int i, j;
  for (i = 0; i < height; i++) {
    for (j = 0; j < width; j++) {
        printf("%d ", array[i][j]);
    }
    printf("\n");
  }
}

and you will call it as:

print_array(height, width, array);

Because in C you are not sending arrays, just pointers, the previous definition is equal to a definition when you send a pointer (to an array of width integers) which you can define as:

void print_array (int height, int width, int (*array)[width]) {
   ...
}
Comments