c - 불완전한 형태의 포인터 - 이진 검색 트리에 문자열 삽입
-
20-12-2019 - |
문제
RootNode -> _ left= null의 불완전한 유형에 대한 역 참조 포인터를 얻을 수 있습니다.어떤 아이디어?
또한이 오류가 발생하기 위해 많은 코드가 주석 처리되었지만이 ADT의 형식에 대한 또 다른 질문이 있습니다. 일반적인 바이너리 검색 트리 구조는 노드 클래스와 삽입물이 촬영 및 노드를 반환하는 것과 같은 모든 BST 기능을 갖는 것입니다.그러나 여기서는 다른 구조 TNode 인 루트가있는 별도의 트리 구조를 사용해야합니다.이것은 예를 들어 AddStringTotree 함수에서 나에게 문제가 해결되었습니다. 트리 매개 변수 만 반환하고 가져옵니다.그래서 나는 노드로 보통의 방식으로 그것을 되풀이하는 방법을 모른다.나는 홈페이지로 도우미 기능을 만들었지 만, 확실하지는 않지만 확실하지는 않습니다.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
typedef struct TNode {
struct TNode* _left;
struct TNode* _right;
struct TNode* _key;
} TNode;
typedef struct Tree {
TNode* _root;
} Tree;
Tree* makeEmptyTree();
void destroyTree(Tree* root);
Tree* addStringToTree(Tree* t, char* value);
TNode* addStringToTreeHelper(TNode* node, char* value);
bool lookupInTree(Tree* t, char* value);
void traverse(TNode* root);
struct Tree* wordTree;
struct TNode* wordRoot;
int main() {
if(wordTree = makeEmptyTree()) {
printf("Tree initialized.\n");
/// traverse(wordTree->_root);
addStringToTree(wordTree, "peter");
//printf(wordTree->_root->_key);
//traverse(wordTree->_root);
} else {
printf("Error initializing tree.\n");
}
return 0;
}
Tree* makeEmptyTree() {
struct Tree* theTree = malloc(sizeof(struct Tree*)); // allocate memory for Tree
theTree->_root = NULL;
return theTree;
}
Tree* addStringToTree(Tree* t, char* value) {
if(t->_root == NULL) {
struct Tnode* rootNode = malloc(sizeof(struct TNode*));
rootNode->_left = NULL;
//rootNode = (TNode*)malloc(sizeof(struct TNode));
//strcpy(rootNode->_key, value);
// rootNode->_left = NULL;
// rootNode->_right = NULL;
//printf(rootNode->_key);
} else {
//addStringToTreeHelper(root, value);
}
return t;
}
TNode* addStringToTreeHelper(TNode* node, char* value) {
// node = malloc(sizeof(TNode)); // What is going on
if(strcmp(value, node->_key) < 0) {
node->_left = addStringToTreeHelper(node->_left, value);
} else if(strcmp(value, node->_key) > 0) {
node->_right = addStringToTreeHelper(node->_right, value);
}
return node;
}
void traverse(TNode* root) {
// if(root != NULL) {
// traverse(root->_left);
// printf("%s\n", root->_key);
// traverse(root->_right);
// } else {
// printf("Empty Tree\n");
// }
}
.
2nd 편집
와우 그냥 어리석은 오타.감사합니다.또한 tnode의 _key 변수는 struct tnode * rolls 눈
해결책
struct Tnode* rootNode = malloc(sizeof(struct TNode*));
는
이어야합니다 struct Tnode* rootNode = malloc(sizeof(struct TNode));
포인터에 충분한 메모리를 할당하고 그 다음 그것을 가리키는 것을 가리키는 것입니다.
편집 :
TNode* rootNode
Tnode* rootNode
가 아니어야합니다.
제휴하지 않습니다 StackOverflow