繁体   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