Search code examples
c++clistdsa

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 ?


Solution

  • 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));