Write C code to dynamically allocate one, two and three dimensional arrays (using malloc())
Its pretty simple to do this in the C language if you know how to use C pointers. Here are some example C code snipptes….
One dimensional array
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, count = 0, no_of_elements=5;
// Allocating dynamic array
int *array = malloc(no_of_elements * sizeof(int));
// Accessing one dimensional array
for (i = 0; i<no_of_elements; i++)
array[i] = ++count; // OR *(arr+i) = ++count
for (i = 0; i < no_of_elements; i++)
printf("%d ", array[i]);
return 0;
}
Two dimensional array
There are more than one methods to allocate two dimensional array dynamically but we use only pointer method.
#include <stdio.h>
#include <stdlib.h>
#define ROW 3
#define COLUMN 4
int main()
{
int i, j, count=0;
// Allocating two dimensional dynamic array
int **arr = (int **)malloc(ROW * sizeof(int *));
for (i=0; i<ROW; i++)
arr[i] = (int *)malloc(COLUMN * sizeof(int));
// Accessing two dimensional array
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COLUMN; j++)
{
arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
printf("%d ", arr[i][j]);
}
}
return 0;
}
Three dimensional array
#include<stdio.h>
#include<malloc.h>
#define AXIS_X 3
#define AXIS_Y 4
#define AXIS_Z 5
int main()
{
int ***p,i,j,k,count=0;
// Allocating three dimensional dynamic array
p=(int ***) malloc(AXIS_X * sizeof(int ***));
for(i=0; i<AXIS_X; i++)
{
p[i]=(int **)malloc(AXIS_Y * sizeof(int *));
for(j=0; j<AXIS_Y; j++)
{
p[i][j]=(int *)malloc(AXIS_Z * sizeof(int));
}
}
// Accessing three dimensional array
for(k=0; k<AXIS_Z; k++)
{
for(i=0; i<AXIS_X; i++)
{
for(j=0; j<AXIS_Y; j++)
{
*(*(*(p+i)+j)+k)= ++count; // OR *(*(*(p+i)+j)+k) = ++count
printf("%d ",p[i][j][k]);
}
}
}
return 0;
}
