C语言 在链表中阅读单词



我试图编写一个程序来读取用户输入的每个单词,然后将该单词粘贴到链表中。这是我到目前为止尝试过的,但遇到了 seg 错误,但不太确定我在错误定位/指针方面出了什么问题。(尚未实现 printList(。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 20
typedef struct node{
    char *word;
    struct node *next;
}node_t;
node_t *read(node_t *node);
void printList(node_t *node);
node_t *insertNode(char *word, node_t *node, int size);
int main(int argc, char *argv[]) {
    node_t *start = NULL;
    printf("Enter a sentence:n");
    read(start);

    return 0;
}
void *read(node_t *node){
    int i, size = MAX_LEN;
    char c, *word;
    if(!(word=malloc(size))){
        printf("Out of memory!n");
        exit(EXIT_FAILURE);
    }
    while((c=getchar())!='n'){
        for(i=0;c!=' ';i++){
            word[i]=c;
            if(i>size){
                size=size*2;
                if(!realloc(word, size)){
                    printf("Out of memoryn");
                    exit(EXIT_FAILURE);
                }
            }
        }
        node = insertNode(word,node,size);  
    }
    return node;
}
node_t *insertNode(char *word, node_t *node, int size){
    node_t *new_node, *current;
    new_node = (node_t*)malloc(sizeof(node_t));
    new_node->next = NULL;
    if(!(new_node->word = malloc(size))){
        printf("Out of memoryn");
        exit(EXIT_FAILURE);
    }
    strcpy(new_node->word,word);
    if (node == NULL){
        node = new_node;
        current = new_node;
    }
    else{
        current->next = new_node;
        current = new_node;
    }
    return node;
}

有几个问题:

  • 你的原型和read的实现不匹配;使两者都返回一个node_t *
  • 您有两个用于输入的嵌套循环,一个从stdin读取,另一个循环遍历字符。内循环从未更新其条件,因为c只能由外循环更改。应该只有一个循环,它负责从流读取和写入字符串。
  • 您不保留 realloc 的结果,这意味着当分配的内存的句柄更改时,您不会反映更新。在这些情况下,您将访问已失效的旧句柄。
  • 不要使用空字符终止字符串。
  • 在越界访问内存之前,应重新分配内存。这通常意味着在写入数组之前检查是否放大数组。请注意,对于长度n数组,n本身已经是一个非法索引。
  • getchar的结果应该是一个int,而不是一个char,以便所有有效的输入都不同于你不检查的EOF

可能还有更多问题,列出的问题是与read有关的问题。我还没有研究链表插入。

为了正确终止零字符串,我建议编写一个无限循环,并在可能的重新分配后推迟break条件。敌人示例:

node_t *read(node_t *node)
{
    int size = MAX_LEN;
    int i = 0; 
    char *word = malloc(size);    
    if(word == NULL) {
        printf("Out of memory!n");
        exit(EXIT_FAILURE);
    }
    while (1) {
        int c = getchar();
        if(i >= size) {
            size = size*2;
            word = realloc(word, size);
            if (word == NULL) {
                printf("Out of memoryn");
                exit(EXIT_FAILURE);
            }
        }
        if (c == 'n' || c == EOF) {
            word[i] = '';
            break;
        }
        word[i++] = c;
    }
    node = insertNode(word, node, size);
    return node;
}

我认为错误是由该行引起的

return node;

insertNode.那应该是

return new_node;

最新更新