Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to initialize a 2D array by calling two functions? example: array[starting_rows()][starting_columns()]

I'm in the process of programming the game 4-in-a-row in C language, the user is supposed to enter the size of the board, the maximum 2D array (board) that I'm allowed to accept is 25X25.

In short, can I initialize the size of a 2D array by calling for two functions in which the user enters the size of the board. I'm receiving the error

Variable-sized object may not be initialized

on the line

int arr[starting_rows()][starting_columns()] = { 0 };
like image 819
Razi Al Ashhab Avatar asked May 08 '26 13:05

Razi Al Ashhab


1 Answers

In short, can I initialize the size of a 2D array by calling for two functions in which the user enters the size of the board (?)

No.
Perhaps in the next version of C (C24)?

int arr[starting_rows()][starting_columns()] is a variable length array (VLA). C presently does not allow initialization of VLAs.

Zero fill it with memset(arr, 0, sizeof arr). @Weather Vane

Alternatively, define and initialize a maximal sized array: int arr[25][25] = { 0 } and use a subset of it. @Lundin


For OP, I suggest the 2nd approach. Get user input and handle potential out-of-range values, incomplete input, input errors, etc. and then, if all is good, proceed to array declaration.

like image 67
chux - Reinstate Monica Avatar answered May 11 '26 04:05

chux - Reinstate Monica