16.6 – Struct – Dynamic memory allocation

by subbu on September 18, 2014

Dynamic memory allocation of a struct variable

Memory allocation of a struct instance (variable) can be allocated during the runtime in the heap of the memory using malloc(). We will see how it can be done step by step

struct num
{
 int x;
 int y;
};

struct num *p;

“p” is a pointer to struct num type of instance, which is capable to store the address of struct num type of instance

p=(struct num*)malloc(sizeof(struct num));

“sizeof(struct num)” gives the size of struct num instance, malloc() selects the memory in the heap segment of specified size and returns the address of allocated memory. As the address returned by malloc() is of void type, it must be type casted to struct num type of pointer before assigning to struct num type of pointer “p”

Now “p” could access every member of struct num instance using pointer to operator -> as p->x and p->y

Pointer to struct variable

#include<stdio.h>
struct num
{
 int x;
 int y;
};
int main()
{
 struct num *p;
 p=(struct num*)malloc(sizeof(struct num)); /* runtime memory allocation of struct instance */
 p->x=10;
 p->y=20;
 printf("Sum: %d",p->x+p->y);
 free(p);   /* de-allocating the memory of struct instance */
 return 0;
}

Self referential struct member

If a struct member is a pointer to the instance (variable) of same struct type then the member is called self referenced struct member

struct node
{
 int data;
 struct node *link;
};

Here struct node has two members, which are data to store an integer value and link  to store the address of another struct node type of instance

struct node *head=NULL;

head pointer

head is pointer to struct node type of instance, which is assigned with NULL

head=(struct node*)malloc(sizeof(struct node));

creating first node

Allocates the memory allocation of struct node type of instance and its address is assigned to head.

head->data=10;
head->link=(struct node*)malloc(sizeof(struct node));

first node

Here head->data is assigned with 10 and head->link is again assigned with the address of another struct node type of instance

head->link->data=20;

second node

Here head->link->data, that is 65508->data is assigned with 20
Now head->data is 10
head->link->data is 20

#include<stdio.h>
struct node
{
 int data;
 struct node *link;
};
int main()
{
 struct node *head=NULL;
 head=(struct node*)malloc(sizeof(struct node));
 head->data=10;
 head->link=(struct node*)malloc(sizeof(struct node));
 head->link->data=20;
 printf("%d\t%d",head->data,head->link->data);
 return 0;
}

Output
10      20

Previous post:

Next post: