C Program to Store record of Employee dynamically
Objective
Write a C program to store Employee records dynamically using pointers and malloc.
Algorithm / Approach
- Define
struct Employee. - Declare a structure pointer:
struct Employee *ptr. - Ask the user for the number of employees
n. - Allocate memory dynamically:
ptr = (struct Employee*) malloc(n * sizeof(struct Employee)). - Loop
ntimes to read data. Use the arrow operator (->) or pointer arithmetic:scanf("%s", (ptr+i)->name). - 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
mallocfunction 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 (->) 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.