我试图输入一个带2个链表的函数。一个具有要打印的值,第二个具有要打印的链接列表值的位置。它给了我一个错误,我把它作为注释放在代码中。
的Structs
typedef int Item;
typedef struct node_struct * link;
typedef struct list_struct * list;
struct node_struct {
Item item;
link next;
};
struct list_struct {
link first;
int length;
};
功能:
list sublist(list A, list pos_list) {
link tempOne;
link tempTwo;
link node = malloc(sizeof *node);
tempOne = pos_list->first;
tempTwo = A->first;
int counter;
while(tempOne->next != NULL)
{
counter = 0;
while(counter < tempOne->item && tempOne->next != NULL)
{
tempTwo = tempTwo->next;
counter = counter+1;
}
node->item = tempTwo->item; //EXC_BAD_ACCESS code:1
node = node->next;
tempTwo = A->first;
tempOne = tempOne->next;
counter = 0;
}
return node;
答案 0 :(得分:0)
代码中存在许多不良做法,这使得您和我们很难理解(并因此调试和维护)此类代码。
typedef int Item
而只是坚持使用int
tempOne
和tempTwo
可能是最差的命名选项,不仅用于调用具有非直观名称的变量(如temp
),还将第一个arg称为{ {1}}和第二个arg为Two
- 尽可能反直觉One
(坦率地说我会称之为node_struct
)和node
看list_struct
评论),但在这个例子中,你不需要node_struct
,它只会给代码增加更多的混淆。list_struct
),这样您就可以轻松处理错误,而不会将内部循环与外部循环混淆除此之外,您还没有指定for loop
是否实际包含相对位置(从先前位置开始的位置)或绝对位置(如数组索引)。我会假设它是绝对的位置。
执行pos_list
后,您需要再次node = node->next;
。或者更确切地说,在线malloc
上使用它之前将它与malloc一起使用并摆脱循环中的node->item = tempTwo->item;
我没有方便的c编译器,所以无法测试它。但我没有看到任何其他问题
修改强>
我注意到子列表的返回值始终只是最后一个节点,而不是链表中的第一个节点 - 这显然也是一个问题。
以下是我编写此代码的方法。请记住,这不是经过调试和测试过的代码,而只是表达了这个想法(如果你愿意,可以先草拟)
malloc