作者:caoxingchi_411 | 来源:互联网 | 2022-12-02 16:23
我是C的初学者.我正在尝试解决一些问题.当我编译代码时,我收到此错误.
[错误]从'void*'无效转换为'triangle*'[-fpermissive]
代码和目的解释如下.
#include
#include
#include
struct triangle
{
int a;
int b;
int c;
};
typedef struct triangle triangle;
//sort_by_area() function is here
int main()
{
int n;
scanf("%d", &n);
triangle *tr = malloc(n * sizeof(triangle));
for (int i = 0; i
正如你所看到我有结构,我试图用输入的数量为它分配内存.并尝试将其用于sort_by_area
功能.但问题是triangle *tr = malloc(n * sizeof(triangle));
行给了我上面提到的错误.
此代码也适用于在线编译器.我尝试使用默认设置在DEV C++上运行此代码.我不知道版本和更改我的编译器的版本.我甚至不知道它是否与编译器版本有关.但我想知道为什么我会收到这个错误.背后的逻辑是什么?
1> dbush..:
这看起来像C代码,但您正在使用C++编译器进行编译.因此,它在你提到的行上抱怨因为malloc
返回a void *
但是你将结果分配给a triangle *
.
在C++中,需要显式强制转换.在C中,a void *
可以隐式地转换为或来自任何对象指针类型.
由于这似乎是C代码而不是C++代码,因此您应该使用C编译器进行编译.