Categories
c

Dynamic Memory Allocation of Arrays in C

In c one can allocate memory for multi-dimensional arrays using malloc. Here is a sample code which one can use for initiating 2d arrays. This is useful in dynamic memory allocation for matrices
[c]
#include “stdio.h”;
#include “alloc.h”;

/* Here we get the array’s dimensions after getting the values of rows
and columns from a file or from the command line using scanf*/
void main()
{
int **matrix;
int rows;
int columns;
matrix = malloc(rows*sizeof( *matrix));
if (matrix != NULL)
{
for(int i=0 ; i < rows ; i++)
{
matrix[i] = (int *)malloc(columns*sizeof( **matrix));
}
} else
{
printf(“Unable to allocate memory for the array\n”);
}
}
[/c]
You can access the above arrays same as you access a 2 dimensional array.