[我的文件在这里(链接已删除)]
我的复制函数不会复制整个列表。
按照@Mat的要求,这里是"copy"函数,但是你仍然需要阅读文件的其余部分来理解我的结构。
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 rangen");
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 = currCopyn");
}
last = curr;
//printf("364debug: %dn",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
在这个简单的测试中,我的函数生成的副本比原始结构少一行。
在问题中的第161行。c中,当您复制链表时,您将原始链表中的元素分配给last
,而不是从新创建的列表中分配前一个。
将该行改为:
last = curr;
:
last = currCopy;