malloc没有转换为struct

Ofe*_*ial 1 c malloc struct declaration type-conversion

我有以下简单的代码:

结构的第一次使用,f工作正常,但我不能malloc n- 我得到一个错误,它无法*无法分配给myValues*.我知道我不应该施放malloc,所以我该怎么做呢?怎么了?

确切的错误:

a value of type "void *" cannot be assigned to an entity of time "myValues *"

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

typedef struct values
{
int a;
char c;
void *pv;
values *next;
} myValues;

int main(){
    myValues f;
    myValues *n = malloc(sizeof(myValues));
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 5

很明显,该程序被编译为C++程序.否则,编译器将发出一个错误,values即未为结构定义声明该名称.

typedef struct values
{
int a;
char c;
void *pv;
values *next;
^^^^^^ 
} myValues;
Run Code Online (Sandbox Code Playgroud)

如果是这样你必须写

myValues *n = ( myValues * )malloc(sizeof(myValues));
Run Code Online (Sandbox Code Playgroud)

因为类型的指针void *不能隐式转换为另一种类型的指针.

(或者您需要将程序完全重写为C++程序,例如替换函数的调用malloc以使用运算符new.)

或者您应该将程序编译为C程序.在这种情况下,你必须写

typedef struct values
{
int a;
char c;
void *pv;
struct values *next;
^^^^^^^^^^^^^ 
} myValues;
Run Code Online (Sandbox Code Playgroud)