c - 我的链接列表有问题

标签 c linked-list

我正在做这个家庭作业,它要求我接受一个巨大的字符串,并将其分成许多子字符串,其中每个字符串由字符串内的“\n”新行值指示,并将其存储到一个链表,例如:

string = "hello world\n i need help!!"

会变成:

string1 = "hello world\n"
string2 = "i need help!!"

我已经编写了这段代码,它将字符串分解为子字符串并将它们存储到单独的节点中。代码本身非常丑陋,需要更多的改进,但我什至无法达到这一点,因为中间似乎发生了一些奇怪的事情,链接列表中的所有字符串都被我添加到的最后一个字符串替换链表...

这是我的代码,如果可以的话请帮忙:

#define eq(A, B) ( A == B )

typedef struct list * link;
typedef char Item;

struct list {
    link next;
    Item *string;
};


void printlist (link ls);
link newLS (char text[]);
link newNode (char text[]);
void insertNode (link next, Item item[]);

link newLS (char text[]) {
    int i = 0;
    int j = 0;
    char temp[(strlen(text))];
    link new = NULL;

    while (text[i] != '\0') {
        temp[j] = text[i];
        if (text[i] == '\n' || text[i+1] == '\0') {
            temp[j+1] = '\0';
            j = -1;
            if (new == NULL) {
                new = newNode(temp);
                printf("new: %s", new->string);
            } else {
                insertNode(new, temp);
                printf("new: %s", new->next->string);
            }
        } 
        i++;
        j++;
    }
    printlist(new);
    return new;
}

link newNode (char text[]) {
    link new = malloc(sizeof(*new));
    assert(new != NULL);
    new->string = malloc ((strlen(text)) * sizeof(char));
    new->string = text;
    new->next = NULL;

    return new;
}

void insertNode (link ls, Item item[]) {
    assert (ls != NULL);
    assert (item != NULL);

    while (ls->next != NULL) {
        ls = ls->next;
    }
    ls->next = newNode(item);

}

int main(int argc, char **argv) {
    link ls;

    ls = newLS("1\n2\n3");
    return 0;
}

我们必须使用这个函数:

link newLS (char text[]) 

最佳答案

  1. #define eq(A, B) ( A == B ) 不是一个好主意,改进的方法是将其定义为 #define eq(A, B)((A)==(B))

  2. 您分配缓冲区,然后不使用它,而是将另一个指针分配给该指针:

    new->string = malloc ((strlen(text)) * sizeof(char));
    new->string = text;
    

    相反,您应该从给定的指针复制数据:

    new->string = malloc ((strlen(text) + 1) * sizeof(char));
    memcpy(new->string, text, strlen(text) + 1);
    

    此外,当您尝试释放分配的内存时,您会遇到段错误,因为new->string没有指向分配的区域。 .

关于c - 我的链接列表有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5567056/

相关文章:

c++ - 如何化简分数

c - 如何区分同一 HTTPS 流量中的不同类型的数据包?

java - 在链表中查找中间节点的输出未按预期输出?

c - 在链接列表的末尾插入节点而不是值

c - C 中的结构初始化错误 : expected expression

从命令行使用静态库编译程序

c - C 中的字符串替换

c - C 声明变量时出错

haskell - Haskell (GHC) 中的列表是如何实现的?

c# - 从单链表中删除节点