Menu Close

Storing Employee record in Linked list

Create Node with Emp details:

We create structure variables in 2 ways.

  1. Variable to structure:
    • We access element using dot(.) operator
    • Memory allocates to all variables in the structure.
  2. Pointer to structure: 
    • We access elements using arrow(->) operator.
    • Memory allocates only to pointer variable
    • We need to allocate memory again using malloc() to that pointer variable.

Variable to structure code:

#include<stdio.h>
struct Emp
{
	int eno;
	char ename[20];
	float esal;
};
struct Node
{
	struct Emp e ;
	struct Node *link;
};
int main()
{
	struct Node *rec;
	rec = (struct Node*)malloc(sizeof(struct Node));
	
	printf("Enter Emp details : \n");
	scanf("%d%s%f", &rec->e.eno, rec->e.ename, &rec->e.esal);
	
	printf("Details are :\n");
	printf("Name : %s\n", rec->e.ename);
	return 0;
}

Pointer to structure code:

  • We create 2 structures
    • one is representing list node.
    • second one is representing emp node.
  • We create pointer to Emp structure in list node structure.
  • Following diagram represents the diagrammatic representation of memory.

Code Program:

#include<stdio.h>
struct Emp
{
	int eno;
	char ename[20];
	float esal;
};
struct Node
{
	struct Emp *e;
	struct Node *link;
};
int main()
{
	struct Node *rec;
	rec = (struct Node*)malloc(sizeof(struct Node));
	rec->e = (struct Emp*)malloc(sizeof(struct Emp));
	
	printf("Enter Emp details : \n");
	scanf("%d%s%f", &rec->e->eno, rec->e->ename, &rec->e->esal);
	
	printf("Details are :\n");
	printf("Name : %s\n", rec->e->ename);
	return 0;
}