【发布时间】:2013-04-27 01:34:28
【问题描述】:
我只需要另一双眼睛来帮助我指出我肯定犯的一个愚蠢的错误。
结构和原型:
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 时出现分段错误。
【问题讨论】:
-
啊啊啊!!!不要在 C 中使用
new作为变量名。你会让所有接触过任何 C++ 的人感到困惑。 -
真的,没想到,只是从node快速切换,所以不会是node* node =...
-
所以
orderedInsert应该返回Node *,但您唯一的返回返回1或0。 -
struct node *node没有任何问题。名称位于不同的空格中。 -
是的,我刚刚将它更改为在帖子中不那么混乱,Shafik 明白了,我返回一个 int 作为节点。
标签: c linked-list segmentation-fault