Home » C programs

C program to declare memory for an integer variable dynamically

Dynamic Memory Allocation Example: In this C program, we are will declare an integer pointer and allocate memory for an integer variable at run time using malloc().

This program is an example of Dynamic Memory Allocation. Here, you will learn how to declare memory at run time for an integer variable? Here we are using malloc() function, which is a predefined function of stdlib.h header file, that is used to declare memory or blocks of memory.

In this example, there is an integer pointer and memory for an integer variable is going to be declaring at run time and the address of dynamically allocated memory will be assigned to the integer pointer. By using this integer pointer we will read an integer number and print the value on the standard output device.

Consider the program:



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

int main()
{
		int *iVar;
		
		iVar=(int*)malloc(sizeof(int));
		
		printf("Now, input an integer value: ");
		scanf("%d",iVar);
		
		printf("Great!!! you entered: %d.\n",*iVar);
		
		free(iVar);
		return 0;
}

Output

Now, input an integer value: 5678
Great!!! you entered: 5678.

Statement: int *iVar

It is an integer pointer that will contain the address of dynamically allocated memory.

Statement: iVar=(int*)malloc(sizeof(int))

Here, malloc() will reserve memory of sizeof(int) bytes and assigns the address of reserved memory to the iVar.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.