4

I have structure:

typedef struct node {
  char *question;
  struct node  *no;
  struct node  *yes;
} node;

Trying to get memory for structure pointer :

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

And got compile error:

 a value of type "void *" cannot be used to initialize an entity of type "node *"   

I told visual studio 2012 to compile C code - Compile as C Code (/TC)

How to solve this problem?

Grzegorz Szpetkowski
  • 36,004
  • 4
  • 86
  • 132
vico
  • 15,367
  • 39
  • 141
  • 262

2 Answers2

2

Assigning malloc()'s void* to your node* is 100% valid C, and your problem is 100% for certain coming from the fact that your compiler is for some reason reading your code as C++ even though you specified /TC.

fieldtensor
  • 3,912
  • 3
  • 25
  • 41
  • 3
    [In C you *should* not cast `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). It's valid, but you should not do it. – Some programmer dude Jul 27 '14 at 19:46
-2

Simply cast the result of malloc.

node *n = ( node* )malloc(sizeof(node));
this
  • 5,159
  • 1
  • 19
  • 49
  • 3
    We're not down voting you because we don't like your casting, we're down-voting you because you're completely failing to notice that the poster's actual issue is that he's accidentally compiling in C++ mode. – fieldtensor Jul 27 '14 at 20:22
  • 1
    @patrick-rutkowski How do you know that? You don't. You are just making assumptions. – this Jul 27 '14 at 20:26
  • 2
    This does not answer the question. The answer to "How do I compile my C code" is not "just rewrite it in C++"... – The Paramagnetic Croissant Jul 27 '14 at 20:40
  • 1
    @TheParamagneticCroissant My code is 100% valid C. And perfectly answers the question *How to solve this problem?* – this Jul 27 '14 at 20:41