C Dynamic Memory Allocation

Get Certified in C Programming and Take Your Skills to the Next Level

Program 1

//  Dynamic Memory in C
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
   system("cls");
   int *ar=NULL;
   int n,i;
   printf("Enter the limit: ");
   scanf("%d",&n);
   //ar=(int*)(malloc(sizeof(int)*n));
   ar=(int*)(calloc(sizeof(int),n));
   printf("Enter an elements: ");
   for(i=0;i<n;i++)
   scanf("%d",&ar[i]);

   for(i=0;i<n;i++)
   printf("\n%d",ar[i]);

   int s=0;
   for(i=0;i<n;i++)
   {
      s=s+ar[i];
   }
   printf("sum is %d",s);
   free(ar);
    return 0;
}













//     int ar[5],n,i;
//     system("cls");
//     printf("Enter the limit");
//     scanf("%d",&n);
//     printf("Enter the elements");
//     for(i=0;i<n;i++)
//     {
//            scanf("%d",&ar[i]);
//     }
//    system("cls");

Program 2

//  Dynamic Memory in C
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
   system("cls");
   int *ptr=NULL,i;
   ptr=(int*)malloc(sizeof(int)*2);
  printf("Enter two elements: ");
  for(i=0;i<2;i++)
    scanf("%d",ptr+i);
    printf("Enter two next elements: ");
  ptr=(int*)(realloc(ptr,sizeof(int)*4)); 

  for(i=2;i<4;i++)
  scanf("%d",ptr+i);

  for(i=0;i<4;i++)
  printf("%d\n",*(ptr+i));
 free(ptr);
 
   return 0;
}

 

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *