0

简而言之,我正在为基本数据库编写真正原始的单链表实现。当用户请求打印索引下列出的元素高于当前数据库中的记录数量时,我不断收到段错误,但只有当差异为 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<index; i++) 
    {
        if(current==NULL) 
        {
            printf("There is no such element");
            is_correct=0;
            break;
        }
        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 个小时在试错法上,但没有收到正确的结果.

4

2 回答 2

1

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

for (i=0; i<index && current!=NULL; i++) 
{
    current=current->next;
}
if (current != NULL)
    print(current);
于 2013-01-12T19:42:29.890 回答
0

UPDATED

In the original code above, replace:

if(is_correct!=0) print(current);

with

if(is_correct!=0 && current != NULL)
    print(current);
else
    printf("Trying to print null List entry\n");

Suppose you have 10 entries in the list and the index happens to be 11.
Then here is what happens at i = 10:

for (i=0; i<index; i++) // i(10) < index(11)
{
    if(current==NULL) // not true as you have a 10th element
    {
        printf("There is no such element");
        is_correct=0;
        break;
    }
    else current=current->next; // current is now NULL as there is no 11th element
}
if(is_correct!=0) print(current); // crash, trying to print NULL
于 2013-01-12T19:49:04.233 回答