Tuesday, September 23, 2014

MALLOC() EXAMPLE IN C PROGRAMMING LANGUAGE

#include <stdio.h>
#include <stdlib.h>
void main()
{
    int n,i,*ptr,sum=0;
    clrscr();
    printf("Enter number of elements: ");
    scanf("%d",&n);
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc
    if(ptr==NULL)
    {
printf("Error! memory not allocated.");
exit(0);
    }
    printf("Enter elements of array: ");
    for(i=0;i<n;++i)
    {
scanf("%d",ptr+i);
sum+=*(ptr+i);
    }
    for(i=0;i<n;++i)
    {
printf("Memory address = %u ",&ptr+i);
    }
    printf("Sum=%d",sum);
    free(ptr);
   getch();
}

No comments:

Post a Comment

15 August vs 26th January

 ध्वजारोहण (Flag Hoisting) और झंडातोलन/ध्वजोत्तोलन (Flag Unfurling) दोनों में अर्थ, परंपरा और प्रक्रिया का अंतर होता है। ध्वजारोहण 15 अगस्त ...