How do i define a 2D array using malloc ? (lets say 10X20).
second, can i increase number of rows or cols without creating a new increased array and copying all data
While malloc()
does not directly support multi-dimensional arrays, there are workarounds, such as:
int rows = 10;
int cols = 30;
int *array = malloc(rows * cols * sizeof(int));
// Element (5,6)
int x = 5;
int y = 6;
int element = array [ x * cols + y ];
While this isn't directly a 2D array, it works, and in my opinion it's the simplest. But if you want to use the [][]
syntax instead, you would have to make pointers to pointers, for instance:
int rows = 10;
int cols = 30;
// Rows
int **array = malloc(rows * sizeof(int*));
// Cols
int i;
for(i = 0; i < rows; i++)
array[i] = malloc(cols * sizeof(int));
// Element (5,6)
int x = 5;
int y = 6;
int element = array[x][y];