sách gpt4 ai đã đi

c - 在非常小的代码片段中寻找 SEGFAULT 原因

In lại 作者:行者123 更新时间:2023-11-30 15:52:35 28 4
mua khóa gpt4 Nike

简单地说,我正在为基本数据库编写单链表的原始实现。当用户请求打印索引下列出的元素高于数据库中当前记录数量时,我不断出现段错误,但仅当差值为 1 时。对于更高的数字,它只会触发我在那里编写的错误系统。

代码是:

void print_spec(List* head)
{
int index, i, is_correct=1;
List * current=NULL; //List is typedef'ed structure consisting variables for data and pointer assumed to be bound to next element in list
printf("\nInput the element index: ");
scanf("%d", &index);
if(head!=NULL)
{
current=head;
for (i=0; i
{
if(current==NULL)
{
printf("There is no such element");
is_correct=0;
phá vỡ;
}
else current=current->next;
}
if(is_correct!=0) print(current); //this function simply prints out variables from element
}
else printf("List is empty, can't print");
}

我猜有一个小错误,但正如我在主题中提到的,我现在正在搜索它大约 4 个小时,花了 2 个小时在试错方法上考虑循环计数器中可能的范围超出,但收到了没有正确的结果。

1 Câu trả lời

循环可能会退出,因为 i==index trong khi current==NULL。在这种情况下,永远不会设置 is_ Correct ,并且当您的程序尝试打印 NULL 列表元素时,它可能会失败。您可以通过将代码更改为类似的内容来避免这种情况并简化循环

for (i=0; i
{
current=current->next;
}
if (current != NULL)
print(current);

关于c - 在非常小的代码片段中寻找 SEGFAULT 原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14297164/

28 4 0
Bài viết được đề xuất: c - gdb - 检测到 SIGSEGV 但无法确定哪个函数和哪一行
Bài viết được đề xuất: c - 从C中的文件读取
Bài viết được đề xuất: c - 链表函数调用
Bài viết được đề xuất: c# - 将字符串转换为字节数组,反之亦然
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com