malloc contiguous 2d array
To malloc a contiguous 2D array in C, you can use a pointer to a pointer. Here's an example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3;
int columns = 4;
int arr = (int)malloc(rows sizeof(int));
for (int i = 0; i < rows; i++) {
arr[i] = (int)malloc(columns sizeof(int));
}
// Access elements in the 2D array
arr[0][0] = 1;
arr[0][1] = 2;
// ...
// Free the memory
for (int i = 0; i < rows; i++) {
free(arr[i]);
}
free(arr);
return 0;
}
In this example, we use malloc
to allocate memory for the 2D array. We first allocate memory for an array of int*
pointers with size rows
. Then, for each row, we allocate memory for an array of int
elements with size columns
. This creates a contiguous block of memory for the 2D array.
To access elements in the array, you can use the syntax arr[row_index][column_index]
. Remember to free the memory using free
for each row and the array itself when you're done using it.