获取C中链接列表的第n个值

时间:2013-12-10 14:51:00

标签: c pointers linked-list return

enter image description here虽然在编写代码并检查了很多次之后我得到了一个断言错误。我不知道为什么。希望你好朋友可以帮助我。这是功能

int GetNth(struct node* head, int index) {
    Node* current = head;
    int count = 0; // the index of the node we're currently looking at
    while (current != NULL) {
        if (count == index) 
            return(current->data);
        count++;
        current = current->next;
    }
    assert(0);  
    // if we get to this line, the caller was asking
    // for a non-existent element so we assert fail.
}

这是我得到的错误。

GetNth: Assertion `0' failed.Aborted (core dumped)
  1. 我怀疑的是,如果该位置的值达到预期,为什么会发生断言测试?由于已经存在退出函数的while循环的return语句。

  2. 如果我对断言测试发表评论,并且如果某个位置的命中/未命中符合预期值,则每次返回0而不是值/ null

  3. 提前致谢!

2 个答案:

答案 0 :(得分:2)

我使用旧时尚printf的

调试这样的代码
int GetNth(struct node* head, int index) {
Node* current = head;
int count = 0; // the index of the node we're currently looking at
if ( index < 0 ) {
    printf( "invalid -ve index passes\n" );
    assert(0);
}
printf( "starting ptr %p\n", current );
while (current != NULL) {
    printf( "checking value %d against %d for ptr %p", count, index, current );
    if (count == index) {
        printf( "found\n" );
        return(current->data);
    }
    count++;
    current = current->next;
}
printf( "not found\n" );
assert(0);  
// if we get to this line, the caller was asking
// for a non-existent element so we assert fail.
}

运行它,看看你得到了什么。如果需要,更改fprintf的printf(stderr。

答案 1 :(得分:1)

除了一些输入/输出问题,你的代码看起来是正确的,我认为问题是你传入的列表是NULL,或者它没有足够的项目。所以你打破了断言失败。

输出问题 - assert(0)不是将错误返回给函数调用者的好方法。 C语言无法让调用者函数检测到断言失败。所以你的过程会崩溃。

也有可能是某人调用您的API的原因是他们不知道该项是否在列表中,因此崩溃该过程并不是该POV的好设计。

输入问题 - 您不验证输入参数是否为正数。或者将其限制为无符号。