我只需要另一双眼睛来帮助我指出我确实犯过的愚蠢错误。
结构和原型(prototype):
typedef struct node {
int data;
struct node *next;
} Node;
Node *orderedInsert(Node *p, int newval);
/* Allocates a new Node with data value newval
and inserts into the ordered list with
first node pointer p in such a way that the
data values in the modified list are in
nondecreasing order as the list is traversed.
*/
功能:
#include "orderedList.h"
#include <stdio.h>
#include <stdlib.h>
Node *orderedInsert(Node *p, int newval){
struct node* new = NULL
new = malloc(sizeof(struct node));
struct node* last = p;
while(1){
if (p == NULL){
if (last == p){
return 1;
}
new->data = newval;
new->next = NULL;
break;
}
if ((last->data <= newval) && (p->data >= newval)){
new->data = newval;
new->next = p;
break;
}
}
return 0;
}
使用任何参数调用 orderedInsert 时出现段错误。
最佳答案
我不认为函数本身是段错误,它可能在您没有向我们展示的调用代码中。尽管这里有几个明显的错误。最明显的是它实际上并没有插入任何东西。此函数生成新节点,但它从不以任何方式更改现有列表,因此该节点是孤立的。其次,它被声明为返回一个指针,但它返回 0 或 1。这不会出现段错误,但如果调用者期望一个指针并以这种方式取消引用它,你就会。
关于c - 查找段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16247412/