【问题标题】:Singly linked list of words单词单链表
【发布时间】:2012-02-06 13:40:59
【问题描述】:

我正在尝试编写一个函数words,它从作为参数传递的文本中生成一个单词的单链表(由空格分隔的字符序列)。结果列表中的单词应与文本中的相同。

不幸的是,程序在运行时出错,您能否解释一下出了什么问题,我也希望能得到一些提示。代码如下:

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

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

void printList(struct node* list){
    struct node* it = list;
    while(it != NULL){
        printf("%s ", it -> word);
        it = it -> next;
    }
    printf("\n");
}

void insertLast(struct node* tail, char* neww){
    tail -> next = (struct node*)malloc(sizeof(struct node));
    tail = tail -> next;
    tail -> word = neww;
    tail -> next = NULL;
}

struct node* words(char* s){
    char* slowo = strtok(s, " ");
    struct node* head;
    struct node* tail;
    if (sizeof(slowo) == 0)
        return NULL ;
    head = (struct node*)malloc(sizeof(struct node));

    head -> word = slowo;
    head -> next = NULL;
    tail = head;
    slowo = strtok(NULL, " ");
    while (slowo != NULL){
        insertLast(tail, slowo);
        tail = tail -> next;
        slowo = strtok(NULL, " ");
    }
    return head;
}

int main() {
    printList(words("Some sentance la al olaalal"));
    getch();
    return (EXIT_SUCCESS);
}

【问题讨论】:

  • 究竟有什么不符合您的预期?尝试准确描述您遇到的单个问题。

标签: c list linked-list words


【解决方案1】:

如果您不想insertLast 在调用函数中设置tail,则必须通过引用传递指针(即作为指向指针的指针。):

void insertLast(struct node** tail, char* neww)

insertLast 中使用适当的取消引用以使其正常工作。

【讨论】:

    【解决方案2】:

    您的 words() 函数在原地修改其参数 (s)。您正在使用字符串文字调用 words(),并且不允许修改字符串文字。为了解决这个问题,您可以使用strdup()malloc()+strcpy()s 放入堆分配的内存中。

    【讨论】:

      猜你喜欢
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多