Dimensions of a two-dimensional array come via USB. How to set the size with them?
int8_t x = GetCharBuf(); int8_t y = GetCharBuf(); int arr[y][x]; Dimensions of a two-dimensional array come via USB. How to set the size with them?
int8_t x = GetCharBuf(); int8_t y = GetCharBuf(); int arr[y][x]; You need to allocate memory dynamically using the malloc function:
int** arr = (int**)malloc(sizeof(int*) * y); for (int i = 0; i < y; ++i) { arr[i] = (int*)malloc(sizeof(int) * x); } Remember to free up memory when it is not needed:
for (int i = 0; i < y; ++i) { free(arr[i]); } free(arr); Well, if your compiler supports variable-length arrays, then you can use it exactly as you wrote: https://ideone.com/lQfCcb
But if not - then you need to use a dynamic array. Two options -
int **array = malloc(sizeof(int*)*y); for(int i = 0; i < y; ++i) array[y] = malloc(sizeof(int)*x); If this is really C, not C ++, a cast of malloc not required.
The second option -
int * array = malloc(sizeof(int)*x*y); But the call to array[i][j] will look like array[i*x+j] .
Source: https://ru.stackoverflow.com/questions/816889/
All Articles