2

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]);

1 Answer 1

5

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]) {
   ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, but how should I pass args from the first function? print_array(height, width, array[][]); ? It throws error
It seems to be a last question. I edited it, like it is in your answer, but firstly I similarly get errors. Then I tried to compile it in the terminal with gcc, but as .c file. It worked. Before that I compiled my code in Clion as .cpp. Is it normal?
I think that variable length arrays are not part of C++.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.