0

我正在尝试逐字读取文件中的单词并将它们存储在数组中。我看到我正在循环遍历单词,但是当我尝试打印数组时,它存储的不是单词而是其他东西。我认为问题与内存分配或取消引用指针有关。

如果我尝试删除 struct 节点中的 * before 数据,这是我通常在这样的示例中看到的,我得到的所有值都是 null。有人对可能出现的问题有任何想法吗?我对 C 很陌生,所以我知道代码可能不是那么好。

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

struct node
{
    struct node *next;
    char *data;
};

struct node *head, *ptr, *temp;

void display();
void words(char filename[]);

int main(void)
{
    char fname[99];

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

    head->data = NULL;
    head->next = NULL;

        printf("\nEnter file name: \n");
    scanf("%s", fname);
    words(fname);
    return 0;

}



void words(char filename[]){
    printf("o hi!, %s\n",filename);
    //open the file
    FILE *file = fopen(filename, "r");
    char *word;
    char string[50];
    while (fgets(string,50,file)){
        word=strtok(string, " \n");
            do {
                printf("Oh hi!, %s\n",word);

                temp = (struct node *) malloc(sizeof(struct node));
                temp->data = word;
                temp->next = head->next;
                head->next = temp;

                printf("!!!%s\n",temp->data);
                //insert_front(word);
            } while (word=strtok(NULL," \n"));
    }
    display();
}


void display()
{
    ptr = head;
    while(ptr->next != NULL)
    {
        ptr = ptr->next;
        printf("%s\n ", ptr->data);
    }
}
4

3 回答 3

1
temp->data = word;

lets temp->data point into the string array. When you call fgets the next time, the contents of string are overwritten, and the node in the list points still at the same place in the array, which now no longer contains the token. You need to copy the token,

temp->data = malloc(strlen(word) + 1);
strcpy(temp->data,word);

to have it persist past the current iteration of the loop.

于 2013-02-08T16:51:36.983 回答
1

When you are setting word = strtok(string, "\n") that is problematic, because string is a local variable and strtok will just give you a pointer inside of that local array.

Try word = strdup(strtok(string, " \n"));

于 2013-02-08T16:51:53.340 回答
0

换行

temp->data = word;

temp->data = strdup(word); /* Or use malloc and strcpy if it is not implemented on your platform*/

data这将使用带有单词副本的新指针填充节点的项目。

于 2013-02-08T16:52:05.817 回答