2017-02-02 1 views
0

여기에 두 개의 구조체가 있습니다. struct 자체가 구조체를 가리 키도록 초기화하는 방법을 모르겠습니다. 이것이 가능한지 확실하지 않습니다.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과 동일한 주소를 가리 키도록 result->root을 얻기 위해 무엇을해야하는지 확실하지.

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

루트에 대한 포인터를 가져 오려고합니다.

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

죄송합니다. 질문이 너무 막히면.

Additional Info

나는 두 개의 구조체를 원한다. 하나는 트리 [setNode]의 노드와 트리의 루트와 다른 멤버 (해당 트리의 뮤텍스와 같은)에 대한 포인터를 포함하는 두 번째 구조체 [집합]을 포함합니다. 그것은 문제가되지 않습니다.

문제점 : 함수에서, 내가 나무 위로 가로 질러 가야 할 수 있도록 setNode* temp = someSet -> root;이 있습니다. 즉, temp는 someSet의 루트를 가리켜 야합니다. 그렇다면 new_set 함수에서 result -> root에 무엇을 할당해야합니까?

+4

'__node'는 두 개의 연속 된 밑줄을 포함하고 있으므로 UB입니다. 그러지 마. – Bathsheba

+10

@Bathsheba UB가 아니지만 그러한 이름은 유보됩니다. –

+0

질문은 레이아웃과 무관합니다 ... –

답변

0

빈 세트에는 요소가 없습니다. 집합이 2 진 검색 트리로 표시되면 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 인 것은 아무 것도 없습니다. 귀하의 기능은 그것을 처리 할 수 ​​있어야합니다.

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** 인수를 받아들이는합니다 재귀 탐색 기능을 원하는 경우 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)); 
     ...   
    } 
} 
관련 문제