无效的“ void *”到“ struct *”的转换

时间:2018-10-10 12:06:36

标签: c struct type-conversion malloc

我是C语言的初学者。我正在尝试练习解决一些问题。而且在编译代码时遇到此错误。

  

[错误]从'void *'到'triangle *'的无效转换[-fpermissive]

代码和用途如下所述。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

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 < n; i++) {
        scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
    }
    sort_by_area(tr, n);
    for (int i = 0; i < n; i++) {
        printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
    }
    return 0;
}

如您所见,我具有结构,并且尝试使用输入量为其分配内存。并尝试将其用于sort_by_area函数。但是问题是triangle *tr = malloc(n * sizeof(triangle));行给了我上面提到的错误。

此代码也可用于在线编译器。我尝试使用默认设置在 DEV C ++ 上运行此代码。我不知道编译器的版本和更改版本。我什至不知道它是否与编译器版本有关。但我想知道为什么会出现此错误。背后的逻辑是什么?

4 个答案:

答案 0 :(得分:8)

这看起来像C代码,但是您正在使用C ++编译器进行编译。因此,它在您提到的行上抱怨,因为malloc返回了void *,但是您正在将结果分配给triangle *

在C ++中,为此需要显式强制转换。在C语言中,void *可以隐式转换为任何对象指针类型或从任何对象指针类型隐式转换。

由于这似乎是C代码而不是C ++代码,因此应使用C编译器进行编译。

答案 1 :(得分:2)

您将此程序编译为C ++程序,并且C ++不允许这种隐式转换。

据我所知,开发C ++使用MinGW,您可以使用-xc选项将程序编译为C程序,或者使用设置->语言标准->并选择所需的语言标准

答案 2 :(得分:2)

代码看起来像C代码,但是您正在使用C ++编译器对其进行编译。

  • 确保文件具有C ++的正确扩展名(而不是.c扩展名)。

  • malloc()默认情况下返回一个(void *)指针,因此您必须在代码中将(void *)强制转换为(triangle *)

  • 但是,如果您正在编写C ++代码,那么我建议不要使用malloc和free,而是尝试在C ++中使用“ new”运算符,因为在实例化对象时,它也会调用构造函数(与malloc不同)。

因此,为了避免复杂性,请在C ++中使用new和delete。


C语言中的代码应类似于(文件a.c)
使用gcc a.c -o a.o
进行编译 使用:./a.o

运行


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct triangle {
  int a;
  int b;
  int c;
};

typedef struct triangle triangle;

int main() {
  int n;
  scanf("%d", &n);
  triangle *tr = (triangle *)malloc(n * sizeof(triangle));
  for (int i = 0; i < n; i++) {
    scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
  }
  //sort_by_area(tr, n);
  for (int i = 0; i < n; i++) {
    printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
  }
  free(tr);
  return 0;
}


C ++中的相同代码看起来像(文件a.cpp)
使用g++ a.cpp -o a.o
进行编译 使用:./a.o运行

#include <iostream>
using namespace std;
struct triangle {
  int a;
  int b;
  int c;
};

int main() {
  int n;
  cin >> n;
  triangle *tr = new triangle[n];
  for (int i = 0; i < n; i++) {
    cin >> tr[i].a >> tr[i].b >> tr[i].c;
  }
  // sort_by_area(tr, n);
  for (int i = 0; i < n; i++) {
    cout << tr[i].a << " " << tr[i].b << " " << tr[i].c << "\n";
  }
  delete [] tr;
  return 0;
}

答案 3 :(得分:0)

triangle *tr = (triangle*)malloc(n * sizeof(triangle));

如上所示更改行。 malloc返回通用指针,因此您需要将其显式转换为所需的指针。

Refer this

相关问题