gpt4 book ai didi

c - 调试简单的c代码,双链表复制

转载 作者:行者123 更新时间:2023-11-30 18:06:17 25 4
gpt4 key购买 nike

[我的文件在这里(链接已删除)]

我的复制功能不会复制整个列表。

根据@Mat的要求,这里是“复制”功能,但您仍然需要阅读文件的其余部分来理解我的结构。

Line copyLineText(Line l){
Line newl = malloc (sizeof( struct node ));
checkMalloc(newl,"copyLineText");
newl->length = l->length;
newl->buffer = malloc((newl->length)* sizeof(char));
checkMalloc(newl->buffer,"copyLineText buffer");
strncpy(newl->buffer, l->buffer, newl->length);
return newl;
}
/* Copy the lines between and including 'from' and 'to' of the textbuffer
* 'tb'.
*
* - The result is a new textbuffer (much as one created with newTB()).
* - The textbuffer 'tb' will remain unmodified.
* - The program is to abort() with an error message if 'from' or 'to' is out
* of range.
*/
TB copyTB (TB tb, int from, int to){
if (from > to || from < 0 || to >= tb->numLines){
printf("Error: the from to is out of range\n");
abort();
}
Line line = tb->begin;
while(line->linePosition != from){
line = line->next;
}

TB tbCopy = malloc (sizeof( struct textbuffer ));

Line last = NULL, curr = line, currCopy;

while( curr != NULL && (curr->linePosition != to + 1) ){
currCopy = copyLineText(curr);

if(last == NULL){
tbCopy->begin = currCopy;
}
currCopy->prev = last;
if(last != NULL){
last->next = currCopy;
//printf("362debug: last->next = currCopy\n");
}
last = curr;
//printf("364debug: %d\n",curr->linePosition);
curr = curr->next;
}

currCopy->next = NULL;
tbCopy->end = currCopy;
tbCopy->numLines = to - from + 1;
return tbCopy;
}

如果你运行我的代码,你会看到:

tb2:2 lines
abcde
fg


tb2copy:2 lines
abcde

通过这个简单的测试,我的函数生成的副本比原始结构少了一行。

最佳答案

在 Question.c 的第 161 行,当您复制链表时,您将原始链表中的元素分配给last,而不是分配创建列表中的上一个。

将该行更改为:

last = curr;

至:

last = currCopy;

关于c - 调试简单的c代码,双链表复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5694226/

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