C – malloc() function

malloc() : Allocates numbers of bytes specified by the Size of Structure.

Prototype: void* malloc(size_t size);

  • “size_t” represents “unsigned” value.
  • On success, it returns base address of allocated block.
  • On failure, it returns NULL.
#include<stdio.h>
#include<stdlib.h>
struct Emp
{
            int num;
            char name[20];
            float salary;
};
int main()
{
            struct Emp* p;
            p = (struct Emp*)malloc(sizeof(struct Emp));
            if(p==NULL)
                        printf(“Memory allocation failed \n”);
            else
                        printf(“Memory allocation success \n”);
            return 0;
}
  • We access locations of structure memory using dot(.) operator.
  • If a pointer is pointing to structure, we use arrow(->) operator to access the location.
#include<stdio.h>
#include<stdlib.h>
struct Emp
{
            int num;
            char name[20];
            float salary;
};
int main()
{
            struct Emp* p;
            p = (struct Emp*)malloc(sizeof(struct Emp));
            if(p==NULL){
                        printf(“Memory allocation failed \n”);
            }
            else{
                        printf(“Enter Emp details :\n”);
                        scanf(“%d%s%f”, &p->num, p->name, &p->salary); 
                        printf(“Name is : %s \n”, p->name);
            }
            return 0;
}
Scroll to Top