Malloc Function in C


The malloc() is a library function that allows C to allocate memory dynamically from the heap. The malloc function simply allocates a memory block according to the size specified in the heap and success it returns a pointer pointing to the first byte of the allocated memory else return NULL pointer.
      Syntax :
             void* malloc ( size_t size)
      Example :
             int *ptr = int* malloc ( 5 * size ( int ) )
             int *ptr = int* malloc ( 5 * 4 )
             int *ptr = int* malloc ( 20 )

Source Code

//malloc in Pointers
#include<stdio.h>
#include<stdlib.h>
int main()
{
    //void* malloc(size_t size)
    int i,n;
    printf("\nEnter The Limit : ");
    scanf("%d",&n);
 
    int *ptr=(int *)malloc(n*sizeof(int));
 
    if(ptr==NULL)
    {
          printf("Memory Not Available ...");
          exit(1);
    }
    for(i=0; i<n; i++)
    {
        printf("Enter a integer : ");
        scanf("%d",ptr+i);
    }
    for(i=0;i<n;i++)
    {
        printf("%d  ",*(ptr+i));  // ptr+1
    }
 
    return 0;
}
 
 
 
To download raw file Click Here

Output

Enter The Limit : 5
Enter a integer : 1
Enter a integer : 2
Enter a integer : 3
Enter a integer : 4
Enter a integer : 5
1  2  3  4  5

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C