自我参照结构和引用

CS学生

如果我有以下代码,如何从根开始访问包含“ left here”的字符串(不只是使用l->data)。

我尝试使用,root->left->data但最终出现段错误,我尝试使用GDB,但是我非常使用它。

编辑:还有没有更好的方法来初始化指针指向的结构?

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;
贾沙尊

你或许应该为那些三分分配内存(rootl,和r)。现在,它们都未初始化,垃圾也是如此(可能也指向垃圾):

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;

现在printf("%s", root->left->data);应该"left here"root->left->right打印类似的内容"right here"

请注意,您必须free在某些时候使用这三个指针。

如果您不想使用动态内存管理(malloc/ calloc+ free),则可以选择在堆栈上而不是堆上分配三个节点。您可以通过声明rootlrstruct nodes而不是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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章