malloc():
- Allocate memory to structures dynamically.
- Allocated block address will be assigned to pointer type variable.
- The prototype is:
Why malloc() function returns void* type?
- Malloc() function can allocate memory to different types of structure types
- C developers provided a generic type(void*) pointer as return value after allocating memory to specified structure.
- We need to type cast the pointer to corresponding structure type.
- Malloc() function allocates size bytes memory and returns base address of memory block.
- It returns NULL pointer if the memory is not available.
#include<stdio.h>
#include<stdlib.h>
struct Emp
{
int id;
char name[20];
float salary;
};
int main()
{
struct Emp *p;
p = (struct Emp*)malloc(sizeof(struct Emp));
if(p==NULL)
{
printf("Out of memory \n");
}
else
{
printf("Enter Emp details : \n");
scanf("%d%s%f", &p->id, p->name, &p->salary);
printf("Name : %s \n", p->name);
}
return 0;
}