【问题标题】:C program not recognizing null pointerC程序无法识别空指针
【发布时间】:2014-02-22 00:35:07
【问题描述】:

我试图在 C 中递归地实现一个插入函数,但我遇到了各种各样的问题。我正在上 CS 入门课程,他们在我们以前接触过 C 实验室之前就开始向我们扔 C 实验室。部分问题是列表指针未被识别为 NULL,我也很确定我使用 malloc 不正确。

#include <stdio.h>
#include <stdlib.h>

#define True 1
#define False 0
typedef int BOOLEAN;

struct Node{
int value;
struct Node *next;
};

void insert(int x, struct Node **pL){
printf("insert\n");
if(*pL == NULL){
    printf("inside if\n");
    struct Node *pN;
    pN = (struct Node*) malloc(sizeof(struct Node));
    (*pN).value = x;
    (*pN).next = NULL;
    return;
}
if (*pL != NULL){
    printf("inside else\n");
    insert(x, &(((*pL)->next)));
}
printf("end insert\n");
};

void printList(struct Node *L){
while (L != NULL){
printf("%d", (*L).value);
printList((*L).next);
}
return;
};

main(){
printf("main\n");
struct Node* L;
//L).next = NULL;
int i;
printf("for loop\n");
for (i = 3; i < 20; i+=2){
    printf("%d\n", i);
    insert(i, &L);
}
printList(L);
};

【问题讨论】:

  • struct Node* L = NULL; 可能会修复一些问题
  • 我已经尝试过了,它只是延迟了不可避免的问题。由于它会递归调用它,最终它会到达需要检查 NULL 的地步,一切都下地狱了。
  • (为了节省我们阅读所有内容的时间)问题到底出在哪里?哪个功能?
  • 插入函数,第一个if语句
  • 哦,我明白了——你创建了 pn,但没有把它放在列表中

标签: c insert null linked-list


【解决方案1】:

首先,在main中你需要初始化L:

struct Node* L = NULL;

其次,在insert 中,当您分配新节点pN 时,您并没有将其分配给pL,即它不会被插入。把它放在insert中的return;之前:​​

*pL = pN;

(您也可以删除return 并将if (*pL != NULL) 更改为else。)

然后,在printList 中,您都在使用while 循环和递归进行迭代。选择一个,而不是两个,例如:

while (L) {
    printf("%d\n", L->value);
    L = L->next;
}

此外,您可以在整个代码中将 (*pointer_to_struct).field 替换为 pointer_to_struct-&gt;field 以获得更好的样式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 2021-09-18
    • 2014-04-11
    相关资源
    最近更新 更多