为什么在迭代C中的单链表时,NULL指针检查不起作用?

use*_*425 0 c null pointers loops singly-linked-list

我正在尝试从堆打印.如果我遇到一个NULL指针我应该打印NULL; 否则,打印它的价值.

样本输出:

1   [2]
2   null
3   null
4   [7, 3]
5   null
6   [7]
Run Code Online (Sandbox Code Playgroud)

但是我的代码因解除引用NULL指针而不断崩溃.

这是我写的测试代码:

void printResult(IntList* intL, int nNode, int nEdge)
{
    int i;
    for (i; i <= 10; i++)
    {
        if (intRest((intL))
        {
            printf("%d", intFirst((intL)[i]));
            intRest((intL)[i]);
        }
        else
            printf(" NULL ");
    }
}

//Here is the definition of functions:
//First
int intFirst(IntList oldL)
{
    return oldL->element;
}

/** rest
 */
IntList intRest(IntList oldL)
{
    return oldL->next;
}
//=================
struct IntListNode
{
    int element;
    IntList next;
};

//===================
typedef struct IntListNode * IntList;
Run Code Online (Sandbox Code Playgroud)

Lih*_*ihO 8

你有单独的链接列表,包含没有存储在连续内存块中的节点(它们相当分散),因此尝试以这种方式遍历其元素:

for (i; i <= 10; i++)
    printf("%d", intFirst((intL)[i]));
Run Code Online (Sandbox Code Playgroud)

由于您访问了错误的内存,导致未定义的行为.你应该做的事情如下:

struct IntListNode * ptr = *intL;
while (ptr) {
    printf("%d", ptr->element);
    ptr = ptr->next;
}
Run Code Online (Sandbox Code Playgroud)