C 结构段溢出

标签 c pointers linked-list structure

我有一个 C 语言程序,它创建一个两部分单链表。
我使用结构来生成列表、节点和节点数据。 其中结构定义为

struct TList {
    struct LNode* first;
    struct LNode* last_left;
};

struct LNode {
    struct LData* data;
    struct LNode* next;
};

列表看起来像[ A B C ][ D E ] 在哪里, list->first = "A"list->last_left = "C"

以下函数重置链接列表中的光标。

void reset_list_cursor(struct TList *list) {

    struct LNode *temp, *temp1, *temp2;
    int i = (list_left_size(list) - 1 );

    for (i; i >= 0; i--) {

        temp = list->last_left;
        temp1 = list->first;

        if (temp != NULL) {

            temp2 = temp1->next;
            while (temp2 != temp) {
                temp1 = temp1->next; 
                temp2 = temp2->next;
            }

            list->last_left = temp1;
        }
    }
    list->last_left = NULL;
}

但是,我遇到了段错误,并且我已将其范围缩小到以下几行...

void reset_list_cursor(struct TList *list) {

    temp1 = temp1->next; 
    temp2 = temp2->next;

我知道你永远不能调用 temp = temp->next->next,但是当你创建一个结构来代替 temp->next 时应该'行得通吗?

最佳答案

首先, temp -> next -> next 没有任何问题,而且语法上也是正确的。在任何涉及循环的情况下,您必须确保在进入循环时检查“下一个”是否为空。包括一个条件,当您进入循环时检查 temp -> next == NULL。这会给你带来奇迹。

这类似于 while(temp1->next!=NULL && temp2->next!=NULL)

希望这有帮助。

关于C 结构段溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149640/

相关文章:

c - 使用链表的堆栈实现不起作用

java - 寻找有效的方法将哈希表的元素提取到单个数组中

c++ - 为什么 printf ("%f",0);给出未定义的行为?

c - Valgrind 的无效写入

c - 在 C 中将指针作为函数参数传递

c++ - 可以使用 std::uintptr_t 来避免越界指针算法的未定义行为吗?

java - 如何使用 drool 从自定义对象列表中查找任何属性的值,然后将其存储到变量中

c - Memcpy 到 malloced 结构内的数组中

c++ - 使用 gcc 插件插入全局变量声明

c++ - 如何在 CLI 中打印表格