简体   繁体   中英

Self referential structs and deferencing

If I have the following code, how do I access the string that contains "left here" starting from the root ? (not just using l->data ).

I tried using root->left->data but ended up with a seg fault, I tried to use GDB but I'm very much a beginner in using it.

EDIT: Also is there a nicer way to initialise the structs that the pointers point to?

struct node
{
  char *data;
  struct node *left;
  struct node *right;
} *root, *l, *r;

root->data = "root here";
root->left = l;
root->right = r;

l->data = "left here";  //the data I need
l->left = NULL;
l->right = NULL;

r->data = "right here";
r->left = NULL;
r->right = NULL;

You should probably allocate memory for those three pointers ( root , l , and r ). Right now, they are all uninitialized and so are garbage (which probably point to garbage as well):

struct node
{
  char *data;
  struct node *left;
  struct node *right;
} *root, *l, *r;

root = malloc(sizeof(struct node));
l    = malloc(sizeof(struct node));
r    = malloc(sizeof(struct node));

root->data = "root here";
root->left = l;
root->right = r;

l->data = "left here";
l->left = NULL;
l->right = NULL;

r->data = "right here";
r->left = NULL;
r->right = NULL;

Now printf("%s", root->left->data); should print "left here" and similarly for root->left->right and "right here" .

Note that you must free those three pointers at some point.

An alternative if you don't want to use dynamic memory management ( malloc / calloc + free ) is to allocate the three nodes on the stack instead of on the heap. You can do this by declaring root , l , and r to be struct node s instead of struct node* s.

struct node
{
  char *data;
  struct node *left;
  struct node *right;
} root, l, r; /* <-- note that they aren't pointers */

void myFunc()
{
    root.data = "root here";
    root.left = &l; /* note the use of & to get the "address of" l */
    root.right = &r; /* same here, but for r */

    l.data = "left here";
    l.left = NULL;
    l.right = NULL;

    r.data = "right here";
    r.left = NULL;
    r.right = NULL;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM