4

I need to be able to pass a 2D array into the scanning function after scanning for the size of the array. Everywhere I've looked has told me that you can't pass 2D arrays without dimensions into a function, but I have no clue any other way to do it.


void scan_arrays (int *array, int row, int column);

int main (void){

  int row;
  int column;

  printf("Enter sizes: ");
  scanf("%d %d",&row,&column);


  int firstarray[row][column];
  int secondarray[row][column];

  printf("Enter array 1 elements:\n");
  scan_arrays(&firstarray,row,column);

  printf("Enter array 2 elements:\n");
  scan_arrays(&secondarray,row,column);

  for(int i = 0; i < row; i++){
    for(int j = 0; j < column; j++){
      printf("%d ",firstarray[i][j]);
    }
    printf("\n");
  }

  for(int i = 0; i < row; i++){
    for(int j = 0; j < column; j++){
      printf("%d ",secondarray[i][j]);
    }
    printf("\n");
  }

  return 0;
}

void scan_arrays (int *array, int row, int column){

  for(int i = 0; i < row; i++){
    for(int j = 0; j < column; j++){
      scanf("%d",&array[i][j]);
    }
    printf("\n");
  }

}```
I've only been coding for a couple of months.
dan
  • 51
  • 3
  • Does this answer your question? [How to pass 2D array (matrix) in a function in C?](https://stackoverflow.com/questions/3911400/how-to-pass-2d-array-matrix-in-a-function-in-c) – Bob__ Nov 18 '19 at 23:59
  • Hi Dan, your closing comment mentions you're new to programming. I thought you may find [this link](https://en.cppreference.com/w/c/language/eval_order) informative. It does not negate the answer. I hope it improves your undertanding. The answer to your question works because it's evaluated at _compile time_. During _run time_, the order of evaluation of your function's parameters isn't guaranteed as specified. I've had unexpected results in my own code because I didn't fully understand this earlier. – Andrew Falanga Nov 19 '19 at 01:02

1 Answers1

5

The function should be declared this way:

void scan_arrays (int row, int column, int array[row][column]);

and likewise for the first line of the function definition. The row and column parameters have to come first so that they are in scope for their usage in the array parameter. The row in the array dimension is technically redundant but an easy way for the code to self-document.

The function would be called like this:

scan_arrays(row, column, firstarray)

and the rest of your code can remain unchanged.


It would be a good idea to do some validation of the user input before defining the arrays: it will cause trouble if they enter garbage, 0, negative numbers, or large numbers that cause stack overflow. The latter problem can be avoided with dynamic allocation:

int (*firstarray)[column] = malloc( sizeof(int[row][column]) );
if ( firstarray == NULL )
    // ...error handling

and the code that uses firstarray can remain unchanged.

M.M
  • 138,810
  • 21
  • 208
  • 365