0

I need a node to point to multiple children (I don't know how many of which I have at compile time).
for the time being I only need the father node to point to at least one child.
but it's pointing to '0', what have I missed?
here is my code

#include <bits/stdc++.h>
using namespace std;

string tokens[10];

typedef struct node
{
    char* value;
    node* children[10]={NULL};
}node;

void connect(node* father,node* child)
{
   // child = (node*) malloc(sizeof(node*));
    if(father->children[0]!=NULL)
        father->children[0]=child;
        cout<<father->children[0]<<endl;
}

int main()
{

node* father_ = (node*) malloc(sizeof(node*));
node* child_ = (node*) malloc(sizeof(node*));
cout<<"before\n";
connect(father_,child_);
cout<<"after\n";

father_->children[0]->value="a";
cout<<child_->value;

}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
Aly Shmahell
  • 511
  • 2
  • 7
  • 18

2 Answers2

2

What's the obsession with pointers? Here a more c++ version.

#include <string>
#include <vector>
#include <iostream>
#include <memory>

struct node
{
    std::string value;
    std::vector<node*> children;
};

void connect(node* father,node* child)
{
    father->children.push_back(child);
}

int main()
{
    auto father = std::make_unique<node>();
    auto child = std::make_unique<node>();

    connect( father.get(), child.get());

    father->children[0]->value="a";

    std::cout << child->value;
}

Live on Coliru

Note:

  • avoid using naespace std
  • don't use malloc and free
  • you don't need to typedef struct in c++
  • use containers such as string and vector
  • avoid c style arrays
  • don't use raw pointers for ownership
Thomas
  • 4,980
  • 2
  • 15
  • 30
  • your code simply works, and I like the pure C++ approach you provided, pretty neat. – Aly Shmahell Apr 17 '16 at 19:37
  • While I could have fixed your issue, I though it better to provide a solution that avoids the problem. – Thomas Apr 17 '16 at 20:25
  • I appreciate your help, truly. while I couldn't completely steer away from pointers in this particular project, I found it useful to use vectors to avoid pointing to pointers. however using c++14 methods and variables is not applicable in my situation. – Aly Shmahell Apr 18 '16 at 01:34
1
if(father->children[0]!=NULL)
    father->children[0]=child;

You only instantiate a father-child relation if the father already has a non-null first child. Change != into == (or even drop that !=NULL part, but then negate the condition).

bipll
  • 11,747
  • 1
  • 18
  • 32