从链接列表

时间:2017-12-13 22:34:37

标签: c arrays pointers linked-list segmentation-fault

我正在尝试编写一个程序来计算文本文档中单词的使用次数。为此,我创建了一个名为wordList的函数,该函数创建了一个链接列表,其中包含每个单词的节点。不幸的是,每当我尝试使用printf从链表中读取单词时,就会出现分段错误。我相信这是因为链表实际上并没有复制任何单词。我想知道如何解决这个问题。目前我不知道该怎么办。感谢:)

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

struct Node {
        int timesUsed;
        char* word;
        struct Node* next;
};

struct Node* wordList(FILE *fp, struct Node* head);
struct Node* createNode(struct Node* head, char* word);
char* title(char* file);//creates file name based on command line input


int main(int argc, char** argv){
    //Access file information---------------------------------------------
    FILE *fp;
    char* fileName = title(argv[1]);
    fp = fopen(fileName, "r");

    //Define Head node--------------------------------------------------------

    struct Node* head = (struct Node*)malloc(sizeof(struct Node));

    if (head == NULL){
        printf("there is not enough memory on your device to continue\n");
    }
    //Access words--------------------------------------------------------

    head = wordList(fp, head);
    printf("%s\n",head->word);


    free(head);
    free(fileName);
    return 0;
}


//Function that is causing problems==================================
struct Node* wordList(FILE *fp, struct Node* head){
    char c;
    char wordHolder[1240];//characters
    int j = 0;
    int count = 0;

    do{
    c = getc(fp);
    printf("%c\n",c);
    if(isalpha(c) || isdigit(c) || c == '\''){
        wordHolder[j] = c;
        j++;
    }
    else{
        if(count){
            char* tempWord = strdup(wordHolder);
            head->word = tempWord;
            head->timesUsed = 1;
            head->next = NULL;
                count = 1;
                j = 0;
                for(i = 0; i< strlen(wordHolder); i++){
                    wordHolder[i] = '\0';
                }
            }

            else{
                head = createNode(head, wordHolder);
                j = 0;
                for(i = 0; i< strlen(wordHolder); i++){
                    wordHolder[i] = '\0';
                }

            }
        }       
    }
    while(c != EOF);
    return head;
}

//Creates a new node at end of list=====================================
struct Node* createNode(struct Node* head, char* word){
    struct Node* temp = head;

    while(temp != NULL){
        temp = temp->next;
    }

    temp = (struct Node*)malloc(sizeof(struct Node));
    temp->timesUsed = 1;
    char* tempWord = strdup(word);
    temp->word = tempWord;
    temp->next = NULL;

    return head;
}


//Creates fileName======================================
char* title(char* file){
    char nameOfFile[500];
    strcpy(nameOfFile, file);
    strcat(nameOfFile, ".txt");
    char* temp;
    temp = strdup(nameOfFile);

    if(temp == NULL){
        printf("Your computer has litte memory.\n");
    }
    return temp;
}

0 个答案:

没有答案