Dynamic memory allocation in C


Examples of calloc() and malloc()

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using malloc() function.

 

#include <stdio.h>

#include <stdlib.h>

int main(){

    int n,i,*ptr,sum=0;

    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);

    }

    printf("Sum=%d",sum);

    free(ptr);

    return 0;

}

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc() function.

#include <stdio.h>

#include <stdlib.h>

int main(){

    int n,i,*ptr,sum=0;

    printf("Enter number of elements: ");

    scanf("%d",&n);

    ptr=(int*)calloc(n,sizeof(int));

    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);

    }

    printf("Sum=%d",sum);

    free(ptr);

    return 0;

}

Example of realloc()

Here, ptr is reallocated with size of newsize.

#include <stdio.h>

#include <stdlib.h>

int main(){

    int *ptr,i,n1,n2;

    printf("Enter size of array: ");

    scanf("%d",&n1);

    ptr=(int*)malloc(n1*sizeof(int));

    printf("Address of previously allocated memory: ");

    for(i=0;i<n1;++i)

         printf("%u\t",ptr+i);

    printf("\nEnter new size of array: ");

    scanf("%d",&n2);

    ptr=realloc(ptr,n2);

    for(i=0;i<n2;++i)

         printf("%u\t",ptr+i);

    return 0;

}

Friends please comment to improve the quality on tutorials, and if you like it follow us on facebook and twitter. You can subscribe via email and receive notification of new post right in your inbox.

 

Related posts:

About author

This article was written by admin

Admin has over twenty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles. Working presently as Development Manager in India. A firm Believer in Knowledge grows when it shared.

Comments

Comments (3)
  1. Piyush says - Posted: April 6, 2013

    But I think this is not possible with microcontrollers right, because they dont have an OS to provide memory from heap. It might be possible with RTOS and linux based platform like ARM or raspberry pi etc. ?

  2. admin says - Posted: April 17, 2013

    Yes Zahiirp you are right, it is quite possible…thanks for sharing link

Leave your comment

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