c - 为什么C链表追加失败

标签 c linked-list append

我是C语言新手,现在正在制作一个用于人脸检测的链表。 下面是在链表末尾追加人脸的结构体和方法。

//Structure for storing a face with x, y and window size
typedef struct Face {
    int window;
    int x;
    int y;
    struct Face* next;
} Face;

//Append face(window, x, y) to the end of linked list starting from head
void push(Face* head, int window, int x, int y) {
     Face* temp = (Face *)malloc(sizeof(Face));
     temp->window = window;
     temp->x = x;
     temp->y = y;
     temp->next = NULL;
     Face* cur = head;
     if (head == NULL) {
         printf("Called\n");
         head = temp;
     } else {
         while (cur->next != NULL) {
             cur = cur->next;
         }
         cur->next = temp;
     }
}

在另一个文件中,可执行文件,我调用了push(head, 1, 2, 3)[这里的head被初始化为NULL]。

屏幕上仅打印“Called”。当我检查链表时,可执行文件中的头部仍然为 NULL。

我不知道为什么头部没有更新,但是当我将它放在同一个文件中时,它似乎工作正常。

最佳答案

这是一个猜谜游戏,因为您没有显示相关代码。

幸运的是,在这种情况下很容易猜到......

您传递给函数的参数的类型为Face *,并且您将其设置为新值(您分配的新结构)。不幸的是,您没有返回该值,也没有确保输入参数能够将数据“传输”回调用上下文。你应该做的是:

void push(Face** head, int window, int x, int y) {
  // all you code here...
  *head = temp
  // rest of code...
}

当你调用该函数时:

push(&head, 1, 2, 3);

关于c - 为什么C链表追加失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31733253/

相关文章:

c++ - 对 'Inventory::insertEnd(Node*, int)' 的 undefined reference

c - 如何使用 void 修改链表节点?

c - 这个 C 代码是如何工作的。我得到 56 作为 '\08' 的输出

C: typedef 结构中的函数指针

c - 为什么这段用于反向打印单向链表的代码段没有按预期工作?

c - 优化以下 hackerrank 程序

c - 堆、栈、文本等不同段与物理内存有何关系?

C 程序在按 escape 时终止

jquery - 添加带有 Append 的 DIV,但没有 CSS 样式

Python 列表追加