How to create an array from user input in C

Program to create an array from user input in C using dynamic memory allocation with malloc function.This program will create an integer array by allocating memory of size entered by an user using malloc function and also elements of the array will be input by user. This way an array can be created of any length.

Program Description:

Program will ask user to enter the size of the array and program will allocate memory of total size = number of elements * size of 1 int.

Program will allocate the the memory and then ask user to enter elements to fill the array. Within a loop all elements will be read by scanf function and value will be stored in the array at respective slot number i.e. value of i variable in the program. Array will be printed and memory allocated will be freed using free() function.

C program to create an array from User input


/*--------------------------------------------------------
* Program for how to create an array from user input in c
*/
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int i,NoOfElements;
	int *arr;//array pointer

	//How many elements you want to store in array?
	printf("How many elements? Enter the size: ");
	//Store size into variable n
	scanf("%d",&NoOfElements);

	//allocate memory dynamically with of 
	//total size = NoOfElements* size of 1 integer i.e. sizeof(int)

	//malloc returns void pointer,means points to nothing
	//typecast it to int* as we want to store int values
	arr=(int*)malloc(NoOfElements*sizeof(int));


	//Check memory is allocated successfully
	//if fails return from the program.
	if(arr==NULL){
		printf("ERROR: MEMORY ALLOCATION FAIL\n");
		return 1;//memory allocation fails - return from here
	}

	//
	printf("Enter %d elements",NoOfElements);

	//fill the array with elements by
	//reading from console screen
	for (i=0; i<NoOfElements; ++i){
		scanf("%d",&arr[i]);
	}



	//display the array	
	printf("Array elements are:\n");
	for(i=0;i < NoOfElements;i++){
		printf("%d\n",arr[i]);

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


Output:
How many elements? Enter the size: 5
Enter 5 elements : 12
23
4
5
67
Array elements are:
12
23
4
5
67

Related Posts