C - program to declare int, char and float variables dynamically.


IncludeHelp 22 September 2016

In this code snippet/program/example we will learn how to declare variables dynamically in c programming language?

In this program we will declare Integer, Character and Float variable dynamically, assign values, print values and free allocated memory after use.

Memory can be allocated at run time by using malloc() library function in c programming language and allocated memory can be released by using free() library function.

Dynamically memory allocation functions are declare in stdlib.h, to access them we are using stdio.h header file.

C Code Snippet/ Program - Declare int, char and float dynamically at Run Time

/*C - program to declare int, char and float variables dynamically.*/
#include<stdio.h>
#include<stdlib.h>

int main(){
	//declare pointer variables
	int   *i;
	char  *c;
	float *f;
	
	//initialize size to pointers
	i=(int*)  malloc(sizeof(int));
	c=(char*) malloc(sizeof(char));
	f=(float*)malloc(sizeof(float));
	
	//assign values
	*i=100;
	*c='N';
	*f=123.45f;
	
	//print values
	printf("value of i= %d\n",*i);
	printf("value of c= %c\n",*c);
	printf("value of f= %f\n",*f);
	
	free(i);
	free(c);
	free(f);
	
	return 0;
}

    value of i= 100
    value of c= N
    value of f= 123.449997




Comments and Discussions!

Load comments ↻






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