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,988
  • 6
  • 90
  • 137
vico
  • 17,051
  • 45
  • 159
  • 315

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,972
  • 4
  • 27
  • 43
  • 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,229
  • 1
  • 22
  • 51
  • 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