0

I've a structure that contains two pointers and a value. It is for a binary tree.

 struct node 
 {
  int value;        //holds value of node
  node *lesschild;  //pointer to lesser value child
  node *greatchild; //pointer to greater value child
 };

And this structure is pointed to by a pointer in a function called addelement and now I want to malloc another structure that is pointed to by one of the pointers in the original node or structure, I'm occurring syntax problems and I am looking for help.

This is what I've for creating another structure that is pointed to by lesschild which is in a structure that is pointed to by ptr.

I'm then trying to change value in the new structure through the double pointer.

ptr->lesschild = &malloc(sizeof(struct node));
ptr->lesschild->value = add;   

Can anyone tell me what I'm missing? Thanks for you help

TryinHard
  • 4,078
  • 3
  • 28
  • 54

1 Answers1

0

You were pretty close, it's:

ptr->lesschild = (node *)malloc(sizeof(struct node)); 
ptr->lesschild->value = add;  // assuming add is an int

malloc already returns a pointer. I'm assuming of course lesschild is actually a node * and you just made a typo.

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • Ok I tried that and now I am getting an error that says "invalid conversion from 'void*' to 'node*' " I should mention that these two lines are in a function that does not return any value. – couchprogramer Jun 25 '15 at 03:05
  • You need to cast the result to `node *`, just like the error says. I added it to my answer. – Blindy Jun 25 '15 at 03:06
  • 3
    @couchprogramer Stop using a C++ compiler! Alternatively, change your tag so it's a C++ question. – autistic Jun 25 '15 at 03:07
  • 1
    See the question entitled ["Do I cast the result of malloc"](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) for more information... – autistic Jun 25 '15 at 03:08
  • This looks like homework so I doubt he can choose his compiler (or even knows what it means). Easier to just add the cast! – Blindy Jun 25 '15 at 03:09
  • The odds are his compiler can be switched to compile either C89 or C99, without even using a different compiler. gcc (`g++ -std=c99`), clang (similar to gcc) and Microsoft C++ (can be switched to C89 only in project settings) are all most commonly used... In fact, I can't think of a single C++ compiler that doesn't have a corresponding C compiler running along-side. – autistic Jun 25 '15 at 03:11