gpt4 book ai didi

c - 尝试打印链接列表时出现段错误

转载 作者:行者123 更新时间:2023-11-30 17:05:59 25 4
gpt4 key购买 nike

有问题的代码是:

currnode = ((currnode)->next); 

在我的打印列表函数中。每次我尝试将当前节点的值更改为下一个节点时,我都会收到段错误。为什么是这样?我已经尝试过这些指针并在网上进行了一些搜索,但无济于事。

#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", &times);


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;
}
}

最佳答案

您可能需要提高警告级别。有一些明显的问题。例如:

insertatfront(&leven, a);

insertatfront() 采用 lnode**,但 &levenlnode***

关于c - 尝试打印链接列表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com