malloc() function (Memory Allocation Function) - C-Tutorial

Latest

Tuesday, 4 October 2016

malloc() function (Memory Allocation Function)

 malloc() function (Memory Allocation Function):   

malloc() function is used to allocate memory for the variables at run time.  The malloc() function reserves a single block of memory with the specified size and returns a pointer of type void.  With this, we can assign it to any type of pointer.  The general form of malloc() function is:

            Syntax:           prtvariable = (casttype*)malloc(size);
Where,
            ptrvariable is a pointer variable of type casttype.
            size represents number of bytes of memory to be allocated.

            Example:        int *X;

            X = (int*)malloc(10);             (or)                  X = (int*)malloc(5*sizeof(int));

For this, memory allocation will be:

X  --------------------->  GARBAGE VALUES

                                                   10 BYTES

/* EXAMPLE PROGRAM FOR MALLOC() FUCNTION */

main()
{
            int *p,i,n;
            clrscr();
            printf("\nEnter how many numbers:");
            scanf("%d",&n);
            p=(int*)malloc(n*sizeof(int));
            printf("\nEnter %d Elements:",n);
            for(i=0;i<n;i++)
            scanf("%d",p+i);
            printf("\nArray Elements Are:");
            for(i=0;i<n;i++)
            printf("     %d",*(p+i));

}

No comments:

Post a Comment