This question already has an answer here:
- Why do we cast return value of malloc? [duplicate] 4 answers
- Do I cast the result of malloc? 26 answers
Can someone please explain to me the difference between
int *x = malloc(sizeof(int));
&&
int *x = (int*)malloc(sizeof(int));
Thanks!
The difference is that you are casting the return of
malloc()
in the second example.malloc()
returns avoid*
pointer, which is automatically and safely promoted to any other pointer type in this case.Therefore casting in this case is not required and should not be done. Check here.