Both statements do the same, and the end result is the same, differing only in details of writing and portability.
I remember that the malloc
function returns a void*
, that is, a generic type pointer , and you can not use it directly without first converting it to the type you want.
With cast
ptr = (int*) malloc (sizeof(int));
In this case it explicitly converts void*
to int*
. This will make the code portable for some very old compilers or for c ++, although in c ++ it has better ways of allocating memory than the malloc
.
No cast
ptr = malloc (sizeof(int));
Here the void*
is automatically promoted to the type of pointer that has left, the ptr
. It means that if ptr
is of type int*
:
int *ptr = malloc (sizeof(int));
The void*
is converted to int*
by the compiler. This gives you more flexibility because if you have to change the type of ptr
is less a place where you have to change things. You can do one more step in this direction if instead of putting sizeof(int)
put the type in sizeof
based on the pointer:
int *ptr = malloc(sizeof(*ptr));
Note that if you want to change the type of ptr
to char*
the whole statement is still valid and nothing else needs to be changed, in which case it will be converted to char*
:
char *ptr = malloc(sizeof(*ptr));
In addition to this, it makes the code more readable because it is less extensive, especially when the types to be allocated are long.
Compare:
unsigned long long *ptr = (unsigned long long*) malloc(sizeof(unsigned long long));
With:
unsigned long long *ptr = malloc(sizeof(*ptr));