C - Pointer memory allocation [duplicate]

2019-08-11 02:02发布

This question already has an answer here:

Can someone please explain to me the difference between

int *x = malloc(sizeof(int));

&&

int *x = (int*)malloc(sizeof(int));

Thanks!

1条回答
我想做一个坏孩纸
2楼-- · 2019-08-11 02:39

The difference is that you are casting the return of malloc() in the second example. malloc() returns a void* 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.

查看更多
登录 后发表回答