Data Structure Algorithms with C Language
About Lesson

malloc (Memory Allocation)

used to allocate a single large block of contiguous memory dynamically with specified size.

 

syntax:

void *malloc(unsigned int n);

 

where n is unsigned int.

 

it will return a void pointer that can be cast to any datatype if successful.  If unsuccessful, it will return NULL.

 

Eg: int *ptr=(int *)malloc(4);

 

//Example Program

#include<stdio.h>

 

void main()

{

    int i,n;

    printf(“Ener the number of integers:”);

    scanf(“%d”,&n);

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

 

    if(ptr==NULL)

    {

        printf(“Memory not allocated”);

        exit(1);

    }

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

    {

        printf(“Enter an integer:”);

        scanf(“%d”,ptr+i);

    }

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

    {

        printf(“%d “,*(ptr+i));

    }

}

You cannot copy content of this page