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结构不被大多数人所青睐,使代码难以阅读。