c - 问题在 C 中初始化双堆叠链表

标签 c

我编写的数据结构涉及一组两个链表,它们相互堆叠。尝试在我的测试工具中初始化集合时,出现段错误。我已经注释掉所有值 setter 以测试我是否可以自己找出错误,但我做不到。

初始化方法的原型(prototype):

测试工具:

int
main( )
{
  list the_list;
  int used = 0;
  int values[MAX_VALUES];
  char input[LINE_LEN];
  char command;
  int argument;
  int num_found;
  bool result;
  set_t lower;
  set_t upper;
  the_list->lower = lower;
  the_list->upper = upper;

 input[0] = '\0';
  input[LINE_LEN-1] = '\0';

  fgets( input, LINE_LEN, stdin );
  while (*input != 'q') {
    num_found = sscanf( input, "%c %d", &command, &argument );

    if (num_found > 0) {
      switch (command) {
        case 'i':
          printf ("Request to initialize the set\n");
          if (num_found == 1) {
            result = set_init( &the_list );
          } else {
            result = set_init( NULL );
          }
          printf ("Returned as %d\n", result);
          break;


                                                        34,0-1         8%

初始化方法:

bool
set_init( list *the_list )
{
  bool initialized = false;
  if (the_list !=NULL ) {
    /* We have space to initialize. */

    the_list->lower->set_size = 0;
   /* the_list->lower->head = NULL;
    the_list->lower->tail = NULL;
    the_list->lower->set_level = 1;
    the_list->lower->ready = true;
    the_list->upper->set_size = 0;
    the_list->upper->head = NULL;
    the_list->upper->tail = NULL;
    the_list->upper->set_level = 2;
    the_list->upper->ready = true;*/
    initialized = true;
    }
  return initialized;
  }

还有我的集合、链表和节点结构的结构定义:

typedef struct _set_node_t {
        test_type_t *data;
        struct _set_node_t *next;
        struct _set_node_t *below;
} set_node_t;

/* the set itself keeps track of the head and the tail of the linked list */
typedef struct {

        int set_size;
        bool ready;
        set_node_t *head;
        set_node_t *tail;
        int set_level;
} set_t;

typedef struct {
        set_t *lower;
        set_t *upper;
}list;

最佳答案

这里唯一可能崩溃的是这一行:

the_list->lower->set_size = 0;

the_list 或 the_list->lower 必须未初始化或为 NULL,或者指向无效或不可访问的内存。

编辑:是的,这一行会崩溃,因为你没有初始化 the_list.lower:

result = set_init( &the_list );

这行会崩溃,因为你传递的是 NULL:

result = set_init( NULL );

关于c - 问题在 C 中初始化双堆叠链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33537562/

相关文章:

c - 我不明白这个程序是如何工作的

c - 为什么是 "any primitive object of K bytes must have an address that is a multiple of K"?

c - 使用条件运算符找到两个数字中最小的数字

将数据从内核空间复制到用户空间

将存储在 char 数组中的字符串部分复制到另一个数组

使用循环变量条件的 C 循环优化

c - 当一个数字写为 0x00...x 意味着什么

控制台仅对所有 double 显示 0

c - C 中的不透明数据类型

c - ls 与 nohup 配合不好