Both instructions do the same, and the end result is the same, differing only in writing and portability details.
Remember that the function malloc
return a void*
, or a generic type pointer, and you cannot use it directly without first converting it to the type you want.
Cast
ptr = (int*) malloc (sizeof(int));
In this case explicitly converts the void*
for int*
. This will make the code portable to some very old compilers or to c++, although in c++ it has better ways to allocate memory than the malloc
.
Cast-less
ptr = malloc (sizeof(int));
Here the void*
is automatically promoted to the type of pointer you have on the left, the ptr
. It means that if ptr
be the type int*
:
int *ptr = malloc (sizeof(int));
The void*
is converted to int*
by the compiler. This gives you more flexibility as if you have to change the type of ptr
is one less place where you have to change things. You can take even one more step in this direction if instead of putting sizeof(int)
put the guy in the sizeof
based on the pointer:
int *ptr = malloc(sizeof(*ptr));
Note that if you want to change the type of ptr
for char*
all instruction is still valid and there is no need to change anything else, in which case it will be converted to char*
:
char *ptr = malloc(sizeof(*ptr));
In addition it ends up giving more readability to the code 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));
Depends on the C version
– Jefferson Quesado