Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Dynamic Memory Allocation using malloc() in C

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 219
    Comment on it

    The malloc is an acronym of "memory allocation". This function allocates the requested size of bytes to a variable and return a pointer of type void.


    Syntax:


    p=(type cast *)malloc(size)
    

    Here p is a pointer.


    Example: Calculate the sum to element using malloc()


    #include <stdio.h>
    #include <stdlib.h>
    int main(){
        int n,i,*p,total=0;
        printf("Enter number of elements: ");
        scanf("%d",&n);
        p=(int*)malloc(n*sizeof(int));  //memory allocated
        if(p==NULL)                     
        {
            printf("No Space available");
            exit(0);
        }
        printf("Enter elements of array: ");
        for(i=0;i<n;++i)
        {
            scanf("%d",p+i);
            total+=*(p+i);
        }
        printf("Sum of elements=%d",total);
        free(p); // used to release space
        return 0;
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: