chevron_left
0 points
8 3 1

C++ create array of size n

posted Jul 20, 2020 1 min read


Instructions to make a cluster from client contribution to C

Program to make an exhibit from client contribution to C utilizing dynamic memory assignment with malloc function. This program will make a whole number cluster by allotting memory of size entered by a client utilizing malloc work and components of the exhibit will be a contribution by the client. Thusly a cluster can be made of any length.

Program Description:

The program will solicit the client to enter the size from the exhibit and the program will dispense memory of all outsize = number of components * size of 1 int.

The program will distribute the memory and afterward request that the client enter components to fill the cluster. Inside a circle, all components will be perused by scanf function, and worth will be put away in the exhibit at a particular opening number for example estimation of I variable in the program. The cluster will be printed and memory apportioned will be liberated utilizing free() work.

#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;
}

 

More Posts

How to find the size of the variable char and char array in C++? Lalit Kumar - Jun 19, 2020
Get the size of an array C++ hhh98hd - Aug 5
How to get the number of elements in the array in C++? Lalit Kumar - Jun 18, 2020
How to find the length of the array in C++? Lalit Kumar - May 15, 2020
Array of length n in C++ Lalit Kumar - Jul 17, 2020
Find the Size of an array in C++ Faizan - Oct 20, 2020
Max size of array in C++ sakshi - Jun 3
C++ program accept five integer from user that will be stored in an array using pointer and print them in reverse order. Ahsan29 - May 7
C++ Pointers and Array Ahsan29 - May 7
Pass 2d array to function c++ zeeshan - Jul 20, 2020