【问题标题】:C cast fails: cannot cast from void* to a C structC 转换失败:无法从 void* 转换为 C 结构
【发布时间】:2013-08-20 19:34:32
【问题描述】:

代码:

#include<stdio.h>
#include<malloc.h>
#include<conio.h>

typedef struct singlylist *nodeptr;
typedef struct singlylist *position;

struct singlylist
{
  int x;
  position next;
}

typedef struct singlylist List;
List L;

int isempty(List A)
{
 return(A.next==NULL);
}

void create()
{
 L=(struct singlylist)malloc(sizeof(struct singlylist));
 L.next=NULL;
}

main()
{
 create();
 if(isempty(L))
 puts("Empty list !!!");
 getch();
}      

错误: 无法从 void* 转换为单一列表。

问题: 我无法弄清楚错误背后的原因。谁能解释一下这是什么错误?

【问题讨论】:

  • 记住你不应该在malloc()memcpy()的情况下投
  • C C++ 请在这两种语言中应用不同的规则。

标签: c++ c list dsa


【解决方案1】:

malloc 返回一个 [void] 指针,'struct singlylist' 根本不是指针。

我对 C 语言有点生疏,但应该可以:

typedef struct singlylist *List;

L = (List) malloc(sizeof(*L));

【讨论】:

  • 是的,我在声明列表时犯了一个错误:)我把它改成了一个指针,它工作了:D 谢谢!
  • 我看到的唯一问题是 (a) 如果这是 C,请不要转换 malloc()(并且不要使用 C++ 中的 malloc),以及 (b) 使用 sizeof(*L)。如果它更改为不同的类型,您的 malloc 调用将更明智。除此之外,它是正确的(对于 C 来说)。
猜你喜欢
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 2021-10-27
  • 1970-01-01
  • 2012-01-08
  • 2016-11-10
相关资源
最近更新 更多