簡體   English   中英

自我參照結構和引用

[英]Self referential structs and deferencing

如果我有以下代碼,如何從根開始訪問包含“ 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;

您可能應該為這三個指針( rootlr )分配內存。 現在,它們都未初始化,因此垃圾也是如此(可能也指向垃圾):

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 ),另一種方法是在堆棧上而不是堆上分配三個節點。 您可以通過將rootlr聲明為struct node s而不是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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM