Find the largest element in an array using dynamic memory allocation

C program to find the largest element in an array using dynamic memory allocation.

Program

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
	int i, n;
    int *data;

    printf("Enter the total number of elements\t:");
    scanf("%d",&n);

    data = (int*)calloc(n, sizeof(int));
    if (data == NULL)
    {
        printf("Error!!! memory not allocated.");
        exit(0);
    }

    printf("\nEnter the numbers\n");
    for(i=0;i<n;i++)
    {
        printf("Number %d\t:",i+1);
        scanf("%d",data+i);
    }

    for(i=1;i<n;i++)
    {
        if(*data < *(data+i))
            *data = *(data+i);
    }
    printf("\nlargest number\t:%d",*data);

    getch();
}

Output

Enter the total number of elements      :7

Enter the numbers
Number 1        :23
Number 2        :32
Number 3        :43
Number 4        :45
Number 5        :67
Number 6        :43
Number 7        :21

largest number  :67

Explanation

In this program, calloc() function is used to allocate dynamic memory. Depending upon number of elements, the required size is allocated which prevents wastage of memory.

calloc() Allocates space for an array elements, initializes them as zero and then returns a pointer to memory in dynamic memory allocation

Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements.
For example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.

In the above program, number of elements 'n' is entered by user. A pointer 'data' pointing to int location is also declared. Now, using calloc(), we will assign the memory to these n numbers dynamically (run time).
data = (int*)calloc(n, sizeof(int));
This statement allocates contiguous space in memory for an array of 'n' elements each of size of int, i.e, 2 bytes. If no memory is allocated, error is displayed and program is terminated.
if (data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}
Numbers are taken as an input from the user using (data+i). And, value is accessed using *(data+i)