Join Regular Classroom : Visit ClassroomTech

Need of Typecasting in Dynamic Memory Allocation in C

General syntax of defining a malloc() function is void *malloc(size_t size). malloc() returns a void pointer. The calloc() function void *calloc(size_t n_elements, size_t size) also needs to be typecast while declaring. It sets all the memory blocks to zero by default unlike malloc().

For storing it in the pointer of required data type (int, float, char etc.) we have to typecast it. Until we typecast a memory allocation the compiler will not get to know that what type of data we are gonna store to through the pointer. That’s why it’s important to typecast.

Lets take an example

Example

/* C program to understand need of typecasting in DMA */
/* www.codewindow.in */
 
#include <stdio.h>
#include <stdlib.h>
 
// Driver code
int main() {
    int n, i;  
    int *p;   // Integer pointer is declared
     
    printf("Enter a valid range: ");
    scanf("%d", &n);
     
    p=(int*)malloc(n*sizeof(int));   // An int array of n elements has been assigned to the pointer
     
    if(p == NULL) {                  // Checking if memory allocation is successful or not
        printf("\nMemory allocation unsuccessful");
        exit(0);
    }
    else {                          // Else memory allocation is successful
        printf("\nMemory allocation successful");
        printf("\nEnter the elements of array: ");
     
        for(i=0; i<n; ++i)
            scanf("%d", p+i);   // Array elements are taken as input
     
        printf("\nElements of the array are: ");
        for(i=0; i<n; i++)
            printf("%d ", *(p+i));  // Print element of the array
    }
    return 0;
}

Input

Enter a valid range: 10
Enter the elements of array: 1 2 3 4 5 6 7 8 9 10 

Output

Memory allocation successful
Elements of the array are: 1 2 3 4 5 6 7 8 9 10 

Explanation

In this above program, “p” is an integer array pointer. n is the number of elements for which memory has to be allocated. Before using in malloc() function “p” has been declared as a integer pointer, but again “p” is typecast inside malloc() as an integer type pointer.

As malloc() and calloc() both return void pointer if not typecast. But p is an integer pointer. Here the typecasting has been done to resolve this mismatch. The similar logic can be given for explaining the need of typecasting in calloc().


Follow Us

You Missed

Also Checkout