简体   繁体   English

将文件中的单词读入C中的节点struct

[英]Read words from file into node struct in c

I'm having trouble with reading word from a file into a node struct. 我在从文件中读取单词到节点结构时遇到麻烦。 This is the code: 这是代码:

//open file
FILE* fp = fopen("fp", "r");

//create node structure
typedef struct node  
{
      char* word;
      struct node* next;
} node;

node* newNode = malloc(sizeof(node));

fscanf(fp, "%s", newNode->word);

printf("w: %s\n", newNode->word);

the fp file looks like this fp文件如下所示

word1
word2
word3
word4

The newNode->word is NULL , why is this? newNode->wordNULL ,为什么呢?

This is because you have not allocated space for the word . 这是因为您尚未为word分配空间。 When you allocate node , only a pointer to the word gets allocated. 当您分配node ,只会分配指向单词的指针。 However, the pointer remains uninitialized until you assign it. 但是,在分配指针之前,指针将保持未初始化状态。 Reading into it using fscanf is undefined behavior, because there is no memory behind it. 使用fscanf对其进行读取是未定义的行为,因为其后没有内存。

One way to deal with it is as follows: allocate a temporary buffer of fixed size large enough to hold the largest word, read the word into it, then allocate the space for the string, copy the content, and set the pointer into the node: 处理它的一种方法如下:分配一个固定大小的临时缓冲区,该缓冲区的大小足以容纳最大的单词,将单词读入其中,然后为字符串分配空间,复制内容,并将指针设置到节点中:

char buf[100];
...
fscanf(fp, "%99s", buf); // 99, not 100, because '\0' must fit in the buf as well
int len = strlen(buf);
newNode->word = malloc(len+1); // +1 for null terminator
strcpy(newNode->word, buf);

newNode->word is just a pointer. newNode->word只是一个指针。 You need to allocate memory to newNode->word before actully storing the data in it! 您需要在将数据强制存储到newNode-> word之前为其分配内存!

node* newNode = malloc(sizeof(node));
newNode->word = (char*) malloc(sizeof(char)*10);
fscanf(fp, "%s", newNode->word);

This shud do the trick. 这个手法可以解决问题。

The newNode->word is NUL because you didn't allocate memory for it. newNode-> word为NUL,因为您没有为其分配内存。 You need either 你需要

typedef struct node  
{
      char word[100];  // maximum word length 99
      struct node* next;
} node;

or 要么

node* newNode = malloc(sizeof(node));
newNode->word = malloc(100);    // allocate space for word

You either need to allocate some space for the string you would like to store and pass a pointer to that space to scanf, or you could use "%ms" to have scanf allocate the space on its own. 您或者需要为要存储的字符串分配一些空间,然后将指向该空间的指针传递给scanf,或者您可以使用“%ms”让scanf自己分配空间。 For the latter you need to pass a pointer to a pointer. 对于后者,您需要将指针传递给指针。 In your case that would be &node->word. 在您的情况下,这将是&node-> word。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM