Wednesday, August 27, 2025

Dynamic Memory allocation using malloc and calloc

Introduction to dynamic memory allocation and use of DMA functions malloc(), calloc(), free(), etc. [Construct a structure for students having roll number, name, and marks; ask the user for the number of students, allocate memory run time, get all data and print given data in table format.]

1. DMA using malloc()

#include<stdio.h>
#include<stdlib.h>
struct stud{
    int num, marks;
    char name[30];
};
void main(){
    int i, n;
    struct stud *p;
    printf("How many number of students:");
    scanf("%d",&n);
    p = (struct stud*) malloc (n*sizeof(struct stud));
    
    if(p==NULL){
        printf("\nMemory not available..");
    }
    printf("Enter Student Details:");
    for(i=0;i<n;i++)
    {
        printf("\nEnter Number:");
        scanf("%d",&p[i].num);
        printf("Enter Name:");
        scanf("%s",&p[i].name);
        printf("Enter Marks:");
        scanf("%d",&p[i].marks);
    }
    printf("\nStudent Details\n Number\t Name\t Marks");
    for(i=0;i<n;i++)
    {
        printf("\n%d\t%s\t%d",p[i].num,p[i].name,p[i].marks);
    }

     free(p);
}


2. DMA using calloc()

#include<stdio.h>
#include<stdlib.h>
struct stud{
    int num,marks;
    char name[30];
};
void main(){
    int i,n;
    struct stud *p;
    printf("How many number of students:");
    scanf("%d",&n);
    p = (struct stud*) malloc (n*sizeof(struct stud));
    //p = (struct stud*) calloc (n,sizeof(struct stud));


    if(p==NULL){
        printf("\nMemory not available..");
    }
    printf("Enter Student Details:");
    for(i=0;i<n;i++)
    {
        printf("\nEnter Number:");
        scanf("%d",&p[i].num);
        printf("Enter Name:");
        scanf("%s",&p[i].name);
        printf("Enter Marks:");
        scanf("%d",&p[i].marks);
    }
    printf("\nStudent Details\n Number\t Name\t Marks");
    for(i=0;i<n;i++)
    {
        printf("\n%d\t%s\t%d",p[i].num,p[i].name,p[i].marks);
    }

     free(p);
}

No comments:

Post a Comment