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);


    return 0;


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.

C Advance Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.