Example of dynamic array in C Programming

Dynamic array in C using malloc library function. Program example will create an integer array of any length dynamically by asking the array size and array elements from user and display on the screen. You can read here how memory allocation in C programming is done at run time with examples.

This C program prompts the user to enter the size of the integer array i.e. how many elements he wants to store, and create the memory dynamically for the array. Program calculates the size of the array by multiplying the size entered by user (number of integer elements) with size of 1 integer.  Size of 1 integer will be calculated by using sizeof operator.

For example, if user enters the size equal to 5 (means user wants to store 5 integer elements). So, total size to allocate memory block will be equal to = 5*sizeof(int).

We will pass the size of the array  to malloc function as an argument to create memory block. After creating the memory block for array, program will again prompt to user to enter the elements and using for loop, program will store all 5 elements to memory blocks.

Then program will access all the 5 elements from the array using for loop and display on the screen.

NOTE: Below C program will handle any size of array that you enter. This is the benefits of dynamic array allocation. With static allocation ( static array) , you cannot handle array of multiple size, because you cannot change the size of statically allocated array at run time.

Dynamic array in C example

/*----------------------------------------------------
* Program example of creating dynamic array in C using malloc
*/

#include <stdio.h>
#include <stdlib.h>


int main()
{
	//Creating the int pointer to store
	//the address  return by malloc
	int *ptr=NULL;

	//Declaring the variable i for array index to use in for loop
	//to access the array elements. len will be used to calculate
	//size of array and in for loop condition.
	int i,len=0;

	//Prompt user to enter the size of array
	printf("ENTER THE SIZE OF ARRAY:");

	//Reading the array size and storing in len variable 
	scanf("%d",&len);

	//allocating the dynamic memory and store the address
	//returned by malloc. malloc returns address keeping in 
	//void pointer. Since, we want to store int type of 
	//data so, type cast it into int pointer.
	//
	ptr=(int*)malloc(len*sizeof(int));

	//Ask the user to enter all the elements
	printf("ENTER THE ELEMENTS:");
	//assigning the  values to the array
	for(i=0;i<len;++i){
		//write the values in memory location
		scanf("%d", &ptr[i]);
	}

	//Read the values from the memory location and 
	//display on the screen
	
	printf("Array elements are \n");
	for(i=0;i<len;++i)
	{		
		printf("%d,", ptr[i]);
	}

	// free the memory
	free(ptr);
	return 0;
}

Output:
ENTER THE SIZE OF ARRAY:5
ENTER THE ELEMENTS:2
3
4
10
6
Array elements are
2,3,4,10,6

Related Posts