我是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/