Saturday, July 9, 2016

Dynamic Memory Allocation


Dynamic memory allocation (DMA) technique is used to allocate or deallocate the memory dynamically i.e. whenever we need the memory size. Using this concept space size can be saved.

Syntax:

datatype *array = (type casting ) malloc (num * sizeof (type));
datatype *array = (type casting ) calloc (num * sizeof (type));
array = realloc (array);
free (array);


Program to enter name and roll number of student and display it using Dynamic Memory Allocation Concept



#include<stdio.h>
#include<string.h>
int main()
{
    char name[5][10], tname[10];
    int roll[5],temp,i,j;
    for (i=0;i<5;i++)
    {
        printf("Enter the roll number and name : ");
        scanf("%d %s",&roll[i],name[i]);

    }
    for(i=0;i<4;i++)
    {
        for (j=i+1;j<5;j++)
        {
            if (strcmp(name[i],name[j])>0)
            {
                temp=roll[i];
                roll[i]=roll[j];
                roll[j]=temp;
                strcpy(tname,name[i]);
                strcpy(name[i],name[j]);
                strcpy(name[j],tname);

            }
        }
    }
    for(i=0;i<5;i++)
    {
        printf("%d\t%s\n",roll[i],name[i]);
    }
    return 0;
}


Program to calculate sum and average of entered numbers



#include<stdio.h>
int main()
{
    int a[10],*b,i;
    float sum=0,avg;
    b=a;
    printf("Enter 10 numbers : ");
    for (i=0;i<10;i++)
    {
        scanf(" %d",a+i);
        sum+=*(a+i);

    }
    avg=sum/10;
    printf("%d %2f",sum,avg);
    return 0;
}

Program to calculate sum and average of entered numbers using Dynamic Memory Allocation Concept



#include<stdio.h>
void calculate(float a[]);
int main()
{
    float a[10];
    int j;
    printf("Enter 10 numbers");
    for(j=0;j<10;j++)
    {                                                                 
        scanf("%f",&a[j]);
    }
    calculate(a);
    return 0;
}
void calculate(float a[10])
{
    int i;
    float sum=0,avg;
    for(i=0;i<10;i++)
    {
        sum+=a[i];
    }
    avg=sum/10;
    printf("The sum of 10 numbers is %f",sum);
    printf("\n");
    printf("The average is %2f",avg);
}

No comments:

Post a Comment