我在上课时遇到问题。 我在递归打印spheres
链表时特别遇到麻烦。 每当程序在特定部分运行时:
ss=ss->next;
有一个Segmentation fault: 11
.问题可能是什么?(注意:我已经在 rgb and
vec' and
sphere_list , and left out
包含了必要的structs
球体,以免使代码混乱。
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 EMPTYn");
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;
}
试试这个:
void sl_print(sphere_list *ss)
{
if(ss==NULL){
printf("SPHERE LIST EMPTYn");
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++;
}
}
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 结构体不受大多数人的青睐,使代码更难阅读。
您在循环条件中出错。你必须测试下一个值,因为这就是你继续sphere_list的原因。
void sl_print(sphere_list *ss)
{
sphere_list *tmp = ss;
if(ss==NULL)
printf("SPHERE LIST EMPTYn");
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;
}
改 性*