1

我遇到了我正在爲類工作的項目的問題。我特別在遞歸地打印spheres的鏈表時遇到了麻煩。每當程序運行在特定部分時:循環鏈接列表的分段錯誤

ss=ss->next; 

有一個Segmentation fault: 11。問題是什麼? (注:我已經包含了必要的structsand sphere_list , and left out RGB and vec`以便不弄亂代碼。)

typedef struct sphere { 
    vec *center; 
    double radius; 
    rgb *color; 
} sphere; 

typedef struct sphere_list sphere_list; 
/* convention: NULL is the empty sphere list */ 
struct sphere_list { 
    sphere *s; 
    sphere_list *next; 
}; 

void sl_print(sphere_list *ss) 
{ 
if(ss==NULL) 
    printf("SPHERE LIST EMPTY\n"); 
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); 
printf("SPHERE LIST:\n"); 
int i=1; 
while(ss->s!=NULL){ 
    printf("\t%d ", i); 
    sphere_print(ss->s); 
    if(ss->next==NULL){ 
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); 
    return; 
    } 
    ss=ss->next; 
    i++; 
    } 
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); 
    return; 
} 
+0

'if(ss == NULL)'。有沒有對應的'else'? –

回答

0

試試這個:

void sl_print(sphere_list *ss) 
{ 
    if(ss==NULL){ 
    printf("SPHERE LIST EMPTY\n"); 
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); 
    printf("SPHERE LIST:\n"); 
    return ; 
    } 
    int i=1; 
    while(ss != NULL){ 
    printf("\t%d ", i); 
    sphere_print(ss->s); 
    ss=ss->next; 
    i++; 
    } 
} 
0

你犯了一個錯誤在你的循環條件下。你必須測試下一個值,因爲這是你在sphere_list上繼續前進的原因。

void sl_print(sphere_list *ss) 
{ 
sphere_list *tmp = ss; 

if(ss==NULL) 
    printf("SPHERE LIST EMPTY\n"); 
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); 
    printf("SPHERE LIST:\n"); 
    int i=1; 
    while(tmp!=NULL){ 
    printf("\t%d ", i); 
    if (tmp->s != NULL) 
     sphere_print(tmp->s); 
    if(tmp->next==NULL){ 
     printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); 
    return; 
    } 
    tmp=tmp->next; 
    i++; 
    } 
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); 
    return; 
} 

修改*

+0

語句'while(ss-> next!= NULL)'不打印列表的最後一個節點。 –

+0

你對!謝謝你,我改變了 –

0
struct sphere_list { 
sphere *s; 
sphere_list *next; 
}; 

你爲sphere *s分配空間,並提出了指針指向有效的內存?我會做這個,只是一個建議。

typedef struct sphere { 
vec *center; 
double radius; 
rgb *color; 
//included the pointer in the struct// 
struct sphere *next 
} sphere; 

此外,typedef結構不被大多數人所青睞,使代碼難以閱讀。