【发布时间】:2016-12-05 02:45:26
【问题描述】:
我正在构建一个 BST 字典树。我在strcmp 行遇到错误,但我不知道为什么。错误是EXC_BAD_ACCESS(Code = 1)。这棵树只是一棵右树,因为文件的第一行是a,所以它是没有左孩子的根。我在错误行旁边评论了。
文本的前几行;
a un, uno, una[Article]
aardvark cerdo hormiguero
aardvark oso hormiguero[Noun]
aardvarks cerdos hormigueros
aardvarks osos hormigueros
我的代码;
#include <stdio.h>
typedef struct node{
char lineOfChar[200];
struct node *left;
struct node *right;
}BST;
typedef struct nodeSec{
BST *next;
}mainLink;
int main(int argc, const char * argv[]) {
struct node *head = malloc(sizeof(BST)); //Define the Head of the linked list of BST
struct nodeSec *headOfHead = malloc(sizeof(mainLink));
headOfHead->next = head;
struct node *current = &head; //Progress down the tree
FILE *file;
file = fopen("/Users/bassammetwally/Desktop/Homework5/text","r");
int times = 0;
char arrayOfLine[200];
while(fgets(arrayOfLine, 200, file)){ //While loop to read lines into the node's array
if (times == 0) // head of linked list to run once
{
for (int counterFirstTime = 0; counterFirstTime < 140; counterFirstTime++)
{
head->lineOfChar[counterFirstTime] = arrayOfLine[counterFirstTime]; // copy the array into the node array
}
times++; // increase times so the previous block would not repeat
}
else {
struct node *temp = malloc(sizeof(BST)); //start a temp node to store the current information for further sorting
for (int counterFirstTime = 0; counterFirstTime < 40; counterFirstTime++)
{
temp->lineOfChar[counterFirstTime] = arrayOfLine[counterFirstTime];//copying line into the node array
}
int q = 2;
while (q == 2)
{
int characterCompare;
if (head != NULL && temp != NULL)
{
characterCompare = strcmp(temp->lineOfChar, head->lineOfChar);//compares the two characters of the array WHERE I GET THE ERROR
}
if (characterCompare > 0) // if temp is bigger..
{
current = head;
head = head->right;// go to the right of the tree
if (head == NULL)// if its NULL and empty then just store it there
{
head = malloc(sizeof(BST));
head = temp;
current->right= head;
break;
}
}
else if (characterCompare < 0){ //since there will not be any duplicates
current = head;
head = head->left;
if (head == NULL)// if its NULL and empty then just store it there
{
head = malloc(sizeof(BST));
head = temp;
current->left = head;
break;
}
}
else if( characterCompare == 0)
{
continue;
}
}
}
head = headOfHead->next;
}
return 0;
}
【问题讨论】:
-
您目前是否只是想将定义插入到您的树中?
标签: c linked-list binary-search-tree