【问题标题】:Segmentation Error with a linked list while loop链表while循环的分段错误
【发布时间】:2014-03-23 00:44:28
【问题描述】:

我正在为课堂工作的项目遇到问题。我在递归打印spheres 的链接列表时特别遇到问题。每当程序在特定部分上运行时:

ss=ss->next;

有一个Segmentation fault: 11。问题可能是什么? (注意:我已经包含了必要的structssphereandsphere_list, and left outrgbandvec`,以免混淆代码。)

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;
}

【问题讨论】:

  • if(ss==NULL)。有没有对应的else??

标签: c while-loop linked-list segmentation-fault dynamic-memory-allocation


【解决方案1】:

您的循环条件出错。您必须测试下一个值,因为这就是您继续使用 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;
}

修改*

【讨论】:

  • 语句while(ss->next != NULL) 没有打印列表的最后一个节点。
【解决方案2】:
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 结构不受大多数​​人的青睐。使代码更难阅读。

【讨论】:

    【解决方案3】:

    试试这个:

     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++;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2020-09-05
      • 1970-01-01
      相关资源
      最近更新 更多