How to declare a variable dynamically in C :
Dynamic memory allocation is a very important concept in C. Using this feature, we can manage memory in runtime. We can allocate a specific amount of byte or memory block for a variable before assigning anything to it.
Following are the two methods mostly used for dynamic memory allocation in C:
- malloc: It is used to allocate a specific number of bytes or memory blocks.
- calloc: It is used to allocate a specific number of bytes or memory blocks and initialize them all with 0.
- free: This method is used to release any dynamically allocated memory.
- realloc: It is used to increase or decrease already allocated memory. We can increase or decrease the amount of memory initialized using malloc or calloc using realloc.
In this post, I will show you how we can declare a variable dynamically in C.
Dynamic variable declaration in C:
Pointer variables are used to hold memory address. In the below program, I will create one pointer variable and allocate some memory to it before assigning a value :
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *c;
c = (char *)malloc(sizeof(char));
printf("Enter a character : ");
scanf("%c", c);
printf("You entered : %c\n", *c);
return 0;
}
Here,
- We created a character pointer variable c.
- Allocate a memory block to this variable using malloc. The size of this memory block is equal to the size of a character.
- Asked the user to enter a character.
- Using scanf, it reads the user input character and then printed out the character back.
If you try to run this program without using the malloc line, it will throw an error.
Using calloc:
We can also write the same program using calloc. It will give similar output:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *c;
c = (char *)calloc(1,sizeof(char));
printf("Enter a character : ");
scanf("%c", c);
printf("You entered : %c\n", *c);
return 0;
}
It works similarly.
You might also like:
- C program to check if a Hexadecimal number is even or odd
- Escape sequence in C explanation with example
- C logical AND, && explanation with examples
- C program to convert a string to uppercase or capitalize all characters
- C program to check if a character is a vowel or consonant
- C program to print squares and cubes of all numbers from 1 to n