我正在嘗試一個示例鏈接列表程序。下面的代碼有什麼問題?當我嘗試訪問值時出現分段錯誤。我無法訪問超出root的值。以下哪項錯誤?鏈接列表
#include<stdio.h>
#include<stdlib.h>
struct node{
int val;
struct node* next;
};
void create(int n,struct node** ref){
struct node *temp,*newnode;
newnode=(struct node*)calloc(1,sizeof(struct node));
newnode->val=n;
newnode->next=NULL;
if(*ref==NULL){
*ref=newnode;
temp=newnode;
}
else{
temp->next=newnode;
temp=newnode;
}
return;
}
int main(){
struct node *root=NULL,*p;
int n,i,j=1;
while(j==1){
printf("enter the value...\n");
scanf("%d",&n);
create(n,&root);
//printf("%d",root->val);
printf("Press 1 to continue..\n");
scanf("%d",&j);
}
p=root;
while(p!=NULL){
printf("%d-",p->val);
p=p->next;
}
printf("\n");
return 0;
}
在'temp-> next = newnode'行中,您可以在不初始化的情況下訪問'temp'。 – mafso