【问题标题】:malloc not casting to structmalloc 不强制转换为结构
【发布时间】:2017-07-25 18:03:29
【问题描述】:

我有以下简单的代码:

结构的第一次使用,f 工作正常,但我不能为n 进行 malloc - 我收到一个错误,它 void* 无法分配给 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));
}

【问题讨论】:

  • 显示准确的错误信息。
  • 你将 C++ 用作 C。
  • 你知道什么是类型转换吗?
  • 使用 C 编译器而不是 C++ 编译器编译代码。

标签: c struct type-conversion malloc declaration


【解决方案1】:

很明显,该程序被编译为 C++ 程序。否则编译器会发出一个错误,指出名称values 没有为结构定义声明。

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

如果是这样,你必须写

myValues *n = ( myValues * )malloc(sizeof(myValues));

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

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

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

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

【讨论】:

  • 对于 C++ 案例,您最好推荐 myValues *n = new myValues()
  • @zwol 我想过这个问题,但我认为即使他使用 C++ 编译器,他也可能希望将程序编译为 C 程序。
  • 所以基本上问题(使用c编译器)是编译器不知道values?为什么它与malloc有关?因为 malloc 也与结构内的对象有关?
  • @OferArial 问题是他正在为 C 程序使用 C++ 编译器。该程序既不会编译为 C 程序,也不会编译为 C++ 程序。
  • @OferArial 如果将程序编译为 C++ 程序,则必须将 malloc 的返回值转换为左侧指针的类型。如果将程序编译为 C 程序,则必须在结构定义中的名称值之前指定关键字 struct。就是这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 2016-09-24
  • 2019-08-25
  • 1970-01-01
  • 2010-12-06
相关资源
最近更新 更多