简体   繁体   中英

C cast fails: cannot cast from void* to a C struct

Code :

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

Error : Cannot cast from void* to singlylist.

Question : I cannot figure out the reason behind the error. Can anyone explain me what error it is ?

malloc returns a [void] pointer, 'struct singlylist' is not a pointer at all.

I'm a little rusty in C, but that should work:

typedef struct singlylist *List;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM