Ananthu Ananthu - 1 month ago 10
C Question

How can i create dynamically allocated array In C

How can I allocate memory to an array dynamically(2D)?

int arr[n];


If I need more or less memory, the dynamic allocation will be more suitable.How can i Do it in C?

Answer

Assuming you have the number of rows "r" and the number of columns "c", you can do this:

int **arr;
arr = malloc(r*sizeof(int*));
for(int i=0; i < r; i++)
{
    arr[i] = malloc(c*sizeof(int));
}

this dynamically allocates an array of pointers to integers, and then allocates arrays of integers to each pointer. Don't forget to delete dynamically allocated arrays when you're done, in this case you should delete the integer arrays first and then the pointer array:

for(int i=0; i < r; i++)
{
    free(arr[i]);
}
free(arr);