在while循环中返回char *

时间:2013-02-18 21:45:12

标签: c

我正在尝试打印链接列表的内容,这是一个char *但是while循环 弄乱了代码:

获取链表中下一项的功能:

char * list_next(list *l)
{
    list *currentPosition = NULL;
    currentPosition = l->next; //since the first node is a dummy value in the singly linked list

    while (currentPosition != NULL)
    {
        return currentPosition->charValue;
        currentPosition = currentPosition->next;
    }

    return NULL;
}

在我的主要内容:

char * item;
while(item = list_next(list))
    printf("%s ",item);

有人可以帮助我吗我很确定问题是在一段时间内的回报 循环,但我似乎无法解决它

4 个答案:

答案 0 :(得分:3)

交换两条线。 return立即退出该功能。它应该读

currentPosition = currentPosition->next;
return currentPosition->charValue;

代替。

(更不用说其他人指出的其他许多错误 - 由于对范围的混淆,在解除引用之前缺少对next的检查等,缺乏实际更新NULL指针的能力。)

答案 1 :(得分:2)

即使交换了返回位置,您的程序仍然只会在每次打印时打印列表中的“第二”项 - 如果存在的话。您需要使用双指针来更新基值,或者想出一些更好的方法来迭代列表。

答案 2 :(得分:0)

您将原始列表传递给list_next()。我相信你总会在永久循环中打印第二个项目。

我建议你可以简化如下:

char *item;
for (item=list->next; // Skip the first item as you said the first node is dummy.
     item != NULL; item=item->next) {
    printf("%s ",item->charValue);
} 

答案 3 :(得分:0)

您在评论中提到,您只需要返回链接列表中的所有值。

function iterate(someNode)
   if someNode ≠ null
     node := someNode
     do
       do something with node.value [1]
       node := node.next
     while node ≠ someNode

来自此Wikipedia articleCC BY-SA

现在,您可以在代码中的位置[1]处简单printf()。但是,您似乎必须返回所有值。 因此,您必须创建一个(可能是动态的)数组。