我正在为一个我正在上课的项目遇到麻烦。我在递归打印spheres
的链接列表方面遇到了麻烦。每当程序在特定部分运行时:
ss=ss->next;
有一个Segmentation fault: 11
。问题是什么?
(注意:我已经包含了必要的structs
范围and
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 :(得分: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++;
}
}
答案 1 :(得分: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;
}
改性*
答案 2 :(得分: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结构。使代码难以阅读。