问题代码是:
currnode = ((currnode)->next);
在我的printlist功能中。每次我尝试将当前节点的值更改为下一个节点时,都会收到分段错误。为什么是这样?我已经玩过这些指针并在线搜索无济于事。
#include<stdio.h>
#include<stdlib.h>
#define RANGE 1000
typedef struct lnode {
int value; struct lnode *next;
} lnode;
void printlist(lnode *list);
void search();
int main(int argc, char *argv){
time_t t;
srand((unsigned) time(&t));
int i, times, num, a, b;
lnode **leven, **lodd;
printf("Please state the amount of numbers to be printed\n");
scanf("%d", ×);
for(i = 0; i < times; i++){
lnode **crnt, **pred;
a = nextnum();
b = (a & 1);
if (b == 0){
printf("even\n");
printf("The value of the even node is: %d\n", a);
/* search(*leven,**crnt,**pred, a); */
insertatfront(&leven, a);
}else{
printf("odd\n");
printf("The value of the odd node is: %d\n", a);
/* search(&leven,crnt, pred, a);*/
insertatfront(&lodd, a);
}
}
printlist(*lodd);
printlist(*leven);
}
int nextnum(){
int i, rand1, num;
rand1 = rand()%RANGE;
return rand1;
}
void getnode(lnode **ptr)
{
*ptr = malloc(sizeof(lnode));
}
int insertatfront(lnode **list, int x){
lnode *new_node, **pred, **crnt;
getnode(&new_node);
if(!new_node) return 0;
new_node->value = x;
new_node->next = *list;
printf("The node at the next is %d\n", new_node->next->value);
*list = new_node;
/*search(*list,&crnt,&pred, x);*/
}
void printlist(lnode *list){
int *val;
int print;
struct lnode *tmp;
lnode *currnode;
currnode = list;
while(currnode != NULL){
val = &((currnode)->value);
printf("%d\n", val);
currnode = ((currnode)->next);
printf("printed successfully\n");
}
printf("done \n");
}
void search(lnode *list, lnode **crnt, lnode **pred, int x)
{
*crnt = list;
*pred = NULL;
while(*crnt) {
if((*crnt)->value == x) return;
*pred = *crnt; *crnt = (*crnt)->next;
}
}
答案 0 :(得分:0)
您可能需要提高警告级别。有一些明显的问题。例如:
insertatfront(&leven, a);
insertatfront()
需要lnode**
,但&leven
为lnode***
。
答案 1 :(得分:0)
最后一个节点的下一个不为空,它是一个未定义的值,所以当程序执行undefinedValue.next时,就发生了分段错误。