簡體   English   中英

指向結構的指針成員以在C中構造自己

[英]Pointing member of struct to struct itself in C

這是我正在使用的兩個結構。 我不確定如何初始化,以便該結構的成員指向結構本身。 我不確定這是否可行。

typedef struct __node 
{
   int value;
   struct __node* left;
   struct __node* right;
}setNode;

typedef struct __set {
   setNode* root;
   //mutex for this set (To be implemented)
}set;

我想初始化set的成員,但不確定如何使result->root指向與set result相同的地址。

set* new_set() 
{ 
  set* result = malloc(sizeof(set));
  result -> root = NULL; // Not sure???
}

我想獲得指向根的指針。

void someOther(set* s)
{
   setNode* temp = s -> root;
   //....
}

抱歉,這個問題太模糊了。

Additional Info

我想要兩個結構。 其中一個包含樹的節點[setNode],第二個結構包含指向樹的根和其他成員(例如該樹的互斥體)[set]的指針。 那不是問題。

問題:在一個函數中,我有setNode* temp = someSet -> root; 這樣我應該能夠遍歷樹,即temp應該指向someSet的根。 那么我應該在new_set函數中為result -> root分配什么呢?

空集不包含任何元素。 如果集合由二進制搜索樹表示,則NULL根指針適用於此。

set* new_set() 
{ 
   set* result = malloc(sizeof(set));
   result -> root = NULL; // Yes, absolutely positively 100% sure
   return s; // Don't forget!
}

如果要獲取指向根的指針,請獲取它。

void someOther(set* s)
{
    setNode* temp = s -> root;
    //!!!!
}

temp為NULL沒什么不對。 您的函數必須能夠處理該問題。 如果需要遞歸遍歷函數,請編寫一個具有setNode*參數的函數:

void someOther(set* s)
{
    setNode* temp = s -> root;
    someOtherDoThisActuallyIMeanItNow (temp);
}

void someOtherDoThisActuallyIMeanItNow (setNode* current)
{
    ...
    if (current) { // <-- here we check that it's not NULL
       ...
       someOtherDoThisActuallyIMeanItNow (current->left);
       ...
       someOtherDoThisActuallyIMeanItNow (current->right);
    } else {
       // do whatever is appropriate for an empty tree/set
    }
}

如果您需要一個遞歸遍歷和修改樹的函數,請使之接受setNode**參數。

void someOtherWithMutation(set* s)
{
    setNode* temp = s -> root;
    someOtherWithMutationNow (&temp); // <---- here
}

void someOtherWithMutationNow (setNode** current) // <---- here
{
    ...
    if (*current) { // <-- here we check that it's not NULL
       ...
       someOtherDoThisActuallyIMeanItNow ((*current)->left);
       ...
       someOtherDoThisActuallyIMeanItNow ((*current)->right);
       ...
       if (...) {
           free (*current);
           *current = NULL;
       }           
    } else {
       // do whatever is appropriate for an empty tree/set
       ...
       *current = malloc(sizeof(setNode));
       ...          
    }
}

暫無
暫無

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

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