开发者

one subtle differs between C and C++

开发者 https://www.devze.com 2023-02-22 09:52 出处:网络
The following C statement is invalid in C++. int *a = malloc(sizeof(*a)); Why? How do you fix it? The answer is :

The following C statement is invalid in C++.

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

Why? How do you fix it?

The answer is :

C performs an implicit conversion for void *, while C++ does not. Use an explicit cast to work around this.

M开发者_Go百科y question is: explicit cast to whom and where? thanks.


In C++ you have to say

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

because casting a void* into an int* isn't implicitly done by the compiler.

Better yet, just use new and delete:

int *a = new int();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号