gpt4 book ai didi

c - 指针指向链表中错误的元素 (C)

转载 作者:行者123 更新时间:2023-11-30 19:43:46 26 4
gpt4 key购买 nike

我想在我的程序中实现一个喜欢的列表:前两个元素已正确插入,但接下来的元素开始指向自身:(如您在我的输出中看到的)

0
(nil)
1
0x7fffb3899340
(nil)
2
0x7fffb3899350
0x7fffb3899350
3
0x7fffb3899350
0x7fffb3899350

这是我的方法,它应该返回指向第一个元素的指针:

Filediff* compare(File f1, File f2){
int line = 0;
Filediff *first = &(Filediff){line, 0, NULL}; //First elem
char c1,
c2;

printf("w1\n");
while ((c1 = fgetc(f1.content)) != EOF && (c2 = fgetc(f2.content)) != EOF)
{
if(c1 == '\n' || c2 == '\n'){
line++;
printf("%p\n", first->next);
if(line >= 2)
printf("%p\n", first->next->next);
first = &(Filediff){line, 0, first}; //insert last elem in new record.
}else if(c1 != c2)
first->charCount++;
printf("%c %c\n", c1, c2);
}

fclose(f1.content);
fclose(f2.content);

return first;
}

我的列表中的一条记录如下所示:

typedef struct Filediff
{
int line;
int charCount;
struct Filediff *next;
} Filediff;

感谢您帮我解决这个问题!

最佳答案

这是在我的案例中实现链表的正确方法。

Filediff* compare(File f1, File f2){
int line = 0;
Filediff *first;
first = (Filediff*)malloc(sizeof *first);
first->line = line;
first->charCount = 0;
first->next = NULL;
char c1,
c2;

while ((c1 = fgetc(f1.content)) != EOF && (c2 = fgetc(f2.content)) != EOF)
{
if(c1 == '\n' || c2 == '\n'){
printf("%d\n", line);
line++;
printf("%p\n", first->next);
if(line >= 2)
printf("%p\n", first->next->next);
Filediff *buf = (Filediff*)malloc(sizeof *first);
buf->line = line;
buf->charCount = 0;
buf->next = first;
first = buf;
//first = &(Filediff){line, 0, first};
}else if(c1 != c2)
first->charCount++;
}

fclose(f1.content);
fclose(f2.content);

return first;
}

关于c - 指针指向链表中错误的元素 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29192179/

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