簡體   English   中英

為什么我的指針數組在C中存在分段錯誤?

[英]Why my array of pointers have a segmentation fault in C?

我試圖通過將char存儲在char數組中,然后訪問下一個節點來存儲下一個數組,使每個樹都包含在數組中,從而使自己的Trie樹實現在C語言中提交單詞列表。節點。 但是,當我調試它時,似乎失去了與下一個節點數組的連接,因為它說它為空。

這是結構:

typedef struct node {
    char c[ALLCHAR];
    struct node *next[ALLCHAR];
} listword;

listword *head;
listword *current;

這是實現:

head = malloc(sizeof(listword));       //Initialize the head
current = head;                        //Pass the pointer to current
dict = fopen(dictionary, "r");         //This is the source of the words

if(dict==NULL) {
    fclose(dict);
    return 1;
}

//Here I iterate char by char in the dict
for(int c=fgetc(dict);c!=EOF;c=fgetc(dict))
{
    int myc=tolower(c)-97;          //The index equivalent to the char
    if(c=='\n') {
            current->c[27]='\0';        //The end of the word
            current=head;           //Pass the start pointer to the current
    } else {
        current->c[myc]=c;          //Here it puts the char in its position
        current=current->next[myc]; //Here I identify my problem, even 
                                    //when I already initialized next it 
                                    //appears as no value
        if(!current) {
            current=malloc(sizeof(listword)); //Here I initialize next 
                                              //if haven't initialized yet
        }
    }
}

嘗試這個,

#include <stdio.h>     
#include <stdlib.h>

typedef struct node {
    char data[1024];
    struct node *next;
} listword;

listword *head = NULL;


// add string to listword
void add(char *value) {
    listword *tmp;

    tmp = (listword*) malloc(sizeof(listword));
    if (tmp) {
        memcpy(tmp, value, sizeof(tmp));

        tmp->next = head;
        head = tmp;
   }
}    

// show data of listword
void show() {
    listword *tmp;

    tmp = head;
    while (tmp) {
        printf("%s\n", tmp->data);          

        tmp = tmp->next;
    }
}

int main() {
    FILE * file;
    char * line = NULL;
    size_t len = 0;
    ssize_t buffer;

    // open
    file = fopen("dictionary", "r");
    if (file == NULL) {
        exit(1);
    }

    // read line of lines of file and add to listword
    while ((buffer= getline(&line, &len, file)) != -1) {
        add (line);
    }

    // close and free file
    fclose(file);
    if (line) {
        free(line);
    }

    // show data
    show ();

    return (0);
}

暫無
暫無

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

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