gpt4 book ai didi

c - 如何将字符串列表存储到节点中?

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:55 25 4
gpt4 key购买 nike

我试图将一个字符串传递给函数,并返回每个节点都包含字符串的链表。因此,在 main 函数中,如您所见

list = newTB("hello\ngood\nworld"); 

然后,newTB 应该返回列表,就像..

[hello]-> [good]-> [world]->null

我的 newTB 函数一定有错误,因为段错误不断出现。

谁能帮帮我..

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

#include "textbuffer.h"

#define MAX_TEXT 256

typedef struct textbuffer *TB;

struct textbuffer {
char *texts;
int count; // counts how many nodes in the list
TB next;
};

void printBuffer(TB tb){
TB curr = tb;
int i=0;
while(curr != NULL){
printf("POS %d : %s\n", i++, curr->texts);
curr = curr->next;
}
}

int linesTB(TB tb) {
return (tb->count);
}

TB newTB (char text[]){
TB newText = malloc(sizeof(struct textbuffer));
char *cpy = (char *)malloc(MAX_TEXT * sizeof(char));
strcpy(cpy,text);
newText->count = 0;
newText->next = NULL;
int i = 0;
int j = 0;

while( cpy[i] != '\0') {
if( j == 0) {
newText->texts = (char *)malloc(MAX_TEXT * sizeof(char));
}
if(cpy[i] == '\n') {
newText->count++;
newText->next = malloc(sizeof(struct textbuffer));
newText = newText->next;
j = 0;
} else {
newText->texts[j++] = cpy[i++];
}
}
return newText;
}

void releaseTB (TB tb) {
TB head = tb;
TB tmp;

while(head != NULL) {
tmp = head;
head = head->next;
free(tmp->texts);
free(tmp);

}
}

int main(int argc, char * argv[]) {
TB list = NULL;
list = newTB("hello\ngood bye\nworld\n");

printf("**THERE ARE %d LINES IN TEXTBUFFER**\n", linesTB(list));
printBuffer(list);
printf("%s\n",dumpTB(list));
releaseTB(list);
return 0;
}

最佳答案

有很多小问题,但这是大问题:

    if(cpy[i] == '\n') {
newText->count++;
newText->next = malloc(sizeof(struct textbuffer));
newText = newText->next;
j = 0;
}

如果 cpy[i] 是一个换行符,你就创建一个 newText。猜猜你不做什么:提前 i。因此,您不断地反复运行这段代码,直到内存不足。

如果我要重写它,我不会逐个字符地扫描代码,而是使用 strchr() 来查找换行符。此外,您已经复制了一次字符串(使用 strdup 会更有效和更容易),使用复制的字符串并将其切碎并将其部分分配给 textblock所以每个 textblock 不需要它自己的字符串。

关于c - 如何将字符串列表存储到节点中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20604377/

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