gpt4 book ai didi

C - 编程数组以存储文本文档中的单词 - malloc 或取消引用问题

转载 作者:行者123 更新时间:2023-11-30 14:21:22 25 4
gpt4 key购买 nike

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

如果我尝试删除结构节点中数据之前的 *(这就是我通常在此类示例中看到的情况),我得到的所有值都是 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);
}
}

最佳答案

temp->data = word;

temp->data指向string数组。当您下次调用fgets时,string的内容将被覆盖,列表中的节点仍然指向数组中的同一位置,现在不再包含 token 。您需要复制 token ,

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

让它持续经过当前的循环迭代。

关于C - 编程数组以存储文本文档中的单词 - malloc 或取消引用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14777371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com