0

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 ?

fabien
  • 1,529
  • 1
  • 15
  • 28
  • Remember You should never cast in case of `malloc()` and `memcpy()` –  Aug 19 '13 at 05:40
  • C **or** C++ please as for casting apply differnt rules in each of those **two** languages. – alk Aug 19 '13 at 12:20

1 Answers1

2

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));
fabien
  • 1,529
  • 1
  • 15
  • 28
  • Yeah I did a mistake in declaring the list :) I changed it to a pointer and it worked :D Thanks ! – Mohammad Hasan Aug 19 '13 at 04:53
  • 3
    Only things I see wrong with this is (a) don't cast `malloc()` if this is C (and don't ***use*** malloc in C++), and (b) use `sizeof(*L)`. If it ever changes to a different type your malloc call will be the wiser. Apart from those, its right (for C , that is). – WhozCraig Aug 19 '13 at 04:55