0
有問題的問題代碼:段錯誤當試圖打印鏈表
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;
}
}
你是否已經通過調試器完成了它?如果您正在編寫數據結構,則調試器中的錯誤通常很明顯。 –
你確定要將val定義爲'int *'並以這種方式將它傳遞給'printf'? –