Conversion from 'void*' to pointer to non-'void' requires an explicit cast

本文探讨了C和C++中空指针赋值的不同处理方式。在C语言中,可以直接将void指针赋值给非void类型的指针;而在C++中,这种操作会导致错误,需要显式地进行类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在混编C和c++时遇到了这样的错误,是个小错误哦,贴出来不怕大家笑,希望可以对我这样的初学者有所帮助,解决方法,就是因为在C语言中可以把空指针付给一个非空直接而不用去详细指明类型,而C++中是强类型语言所以要声明合适的转换类型

ANSI C allowed conversion from a void pointer to a non-void-pointer without explicitly casting

 

In C you can convert void* to non-void* without witing the conversion operator, but in C++ you can't. For example, this code is OK in C:
Code:
int *arr=malloc(16);

but is'll cause the same error as you got in C++ (malloc returns void*, and is forced to be assigned to int*). In C++ you should write (not as C++'sish at it seems ):
Code:
int *arr=(int*)malloc(16);

just defined the type that correspond to your function's declaration using typedef.
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值