Home » C programs

C program to create dynamic memory for integer, character and float

In this C program, we are going to learn how to create memory dynamically for integer, character and float? Here, we are using malloc() function to create the memory at run time.
Submitted by IncludeHelp, on April 14, 2018

Here, we have to declare memory for integer, character and float type at run time, to do the same – we are using malloc() function.

malloc() creates/declares N bytes of memory at run time (dynamically) and returns pointer (declared memory address).

Program to declare memory at rum time for integer, character and float in C



/** C program to create dynamic memory for integer,
 * char and float and read values and print and free
 * the memory
 */
 
#include <stdio.h>
#include <stdlib.h>

// main function
int main()
{
  //In this program we will create memory for integer, char and float 
  // variables at run time using malloc() function 
  // we will release the allocated memory using free() function.

  // Declare an integer pointer
  int *ptr_1;
  
  // Declare an char pointer
  char *ptr_2;
  
  // Declare an float pointer
  float *ptr_3;
  
  // Now allocating memory to each pointer
  // using dynamic memory allocation
  ptr_1 = (int*)malloc(1*sizeof(int));
  ptr_2 = (char*)malloc(1*sizeof(char)*1);
  ptr_3 = (float*)malloc(1*sizeof(float));
  
  printf("\nEnter the value for integer pointer : ");
  scanf("%d",ptr_1);
  
  printf("\nEnter the value for char pointer : ");
  scanf(" %c",ptr_2);
  
  printf("\nEnter the value for float pointer : ");
  scanf("%f",ptr_3);
  
  printf("\nThe value stored in integer pointer is : %d",*ptr_1);
  printf("\nThe value stored in char pointer is : %c",*ptr_2);
  printf("\nThe value stored in float pointer is : %f",*ptr_3);

  free(ptr_1);
  free(ptr_2);
  free(ptr_3);
  
  return 0;
}

Output

Enter the value for integer pointer : 10 
 
Enter the value for char pointer : c 
 
Enter the value for float pointer : 1.2  
 
The value stored in integer pointer is : 10  
The value stored in char pointer is : c  
The value stored in float pointer is : 1.200000


Comments and Discussions!

Load comments ↻





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