Invalid conversion 'void*' to 'struct*' [duplicate]

  • A+
Category:Languages

This question already has an answer here:

I'm beginner in C. I'm trying to practice with solving some problems. And I'm getting this error when I compile my code.

[Error] invalid conversion from 'void*' to 'triangle*' [-fpermissive]

The code and purpose is explained below.

#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; } 

As you can see I have structure and I tried to allocate memory for it with the quantity of input. And try to use it for sort_by_area function. But the problem is triangle *tr = malloc(n * sizeof(triangle)); line gives me the error mentioned above.

Also this code is working for online compilers. I tried to run this code on DEV C++ with default settings. I don't know about the versions and changing the versions of my compiler. I don't even know whether it is about the compiler version. But I am wondering why I'm getting this error. What is the logic behind.

 


This looks like C code, but you're compiling with a C++ compiler. As such, it complains on the line you mentioned because malloc returns a void * but you're assigning the result to a triangle *.

In C++ an explicit cast is required for this. In C, a void * may be implicitly converted to or from any object pointer type.

Since this appears to be C code and not C++ code, you should compile with a C compiler.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: