Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to Store record of Employee dynamically

C Code Example — Structure Programs

ADVERTISEMENT

C Program to Store record of Employee dynamically

Objective

Write a C program to store Employee records dynamically using pointers and malloc.

Algorithm / Approach

  1. Define struct Employee.
  2. Declare a structure pointer: struct Employee *ptr.
  3. Ask the user for the number of employees n.
  4. Allocate memory dynamically: ptr = (struct Employee*) malloc(n * sizeof(struct Employee)).
  5. Loop n times to read data. Use the arrow operator (->) or pointer arithmetic: scanf("%s", (ptr+i)->name).
  6. Loop again to print the data.
main.c
#include<stdio.h>
#include<stdlib.h>
struct Employee {
 int id;
 char name[30];
};
int main( ) {
 struct Employee *ptr;
 int i,n;
 printf("Enter Number of Employee : ");
 scanf("%d",&n);
 ptr=(struct Employee*)malloc(n*sizeof(struct Employee));
  for(i=0;i < n;++i) {
   printf("Enter Name and ID respectively:\n");
   scanf("%s%d",&(ptr+i)->name, &(ptr+i)->id);
  }
  printf("Displaying Information :\n");
  for(i=0;i<n;++i)
   printf("%s\t%d\t\n",(ptr+i)->name,(ptr+i)->id);
 return 0;
}

Expected Output

Enter Number of Employee : 2
Enter Name and ID respectively :
xyz 39
Enter Name and ID respectively :
abc 45
Displaying Information : 
xyz    39
abc    40

Explanation of the Program

  • Standard arrays have a fixed size defined at compile-time. If you don't know how many employees there are until the program runs, you must allocate memory dynamically.
  • The malloc function asks the OS for a specific amount of bytes of memory while the program is running. When accessing structure members via a pointer, we must use the Arrow Operator (-&gt;) instead of the Dot Operator.

Complexity

Time Complexity O(n) - Where n is the dynamic number of employees.
Space Complexity O(n) - Dynamic memory allocated on the heap.
ADVERTISEMENT