0

I'm watching some lectures about pointers and in the demonstration code, the teacher typecasts the result of malloc in the line buffer = (char*)malloc(sizeof(char) * 128);:


#include <stdio.h>

#include <stdlib.h>

int main()

{
    
char *buffer;
    
    buffer = (char*)malloc(sizeof(char) * 128);
    if (buffer == NULL)
    {
        puts("Unable to allocate memory");
        exit(1);
    }
    puts("Buffer allocated");
    free(buffer);
    puts("Buffer freed");
    
    return 0;
}

My question is why. Is this necessary? If I'm already declaring the memory chunk to be allocated to be the sizeof() a char, it seems redundant.

ai88
  • 33
  • 4

1 Answers1

0

malloc returns a void pointer, which in C can be assigned to any other pointer type without casting. My professor used to hate casting it and if we did then he would take off points. The extra explicitness is not necessary.

Ders
  • 1,068
  • 13
  • 16