【发布时间】:2021-03-09 05:27:27
【问题描述】:
当我编译并运行程序时,它说:在函数'addToTheEnd'中:[警告]从不兼容的指针类型初始化//它指向这一行->knot_t *current = start;
如何解决?我是C新手,所以我不明白应该改变什么。我试图理解它,但我无法理解。我的目标是在我运行这个程序时得到一些输出,但没有任何显示。
#include <stdio.h>
#include <stdlib.h>
typedef struct knot {
int number;
struct knot *next;
} knot_t;
int addToTheEnd(knot_t **start, int value) {
knot_t *new_ = (knot_t *)malloc(sizeof(knot_t));
if (new_ == NULL) {
return 1;
}
new_ -> number = value;
new_ -> next = NULL;
if (start == NULL) {
*start = new_;
} else {
knot_t *current = start;
while (current -> next != NULL) {
current = current -> next;
}
current -> next = new_;
}
return 0;
}
void printList(knot_t *start) {
knot_t *current = start;
while (current != NULL) {
printf("%d ", current->number);
current = current -> next;
}
}
void clearList(knot_t *start) {
knot_t *current = start;
while (current != NULL) {
knot_t* trenutni = current;
current = current -> next;
free(trenutni);
}
}
int main() {
knot_t *start = NULL;
int i = 0;
for (i = 0; i < 10; i++) {
if(addToTheEnd(&start, i)) {
printf("Fail\n");
return EXIT_FAILURE;
}
}
printList(start);
clearList(start);
return EXIT_SUCCESS;
}
【问题讨论】:
-
start的类型为knot **,current的类型为knot *。它们的指针类型不兼容,这意味着你做错了。 -
if (start == NULL) {-->if (*start == NULL) {你想检查传递的指针是否是NULL,但是你检查的是本地指针(这总是给你true) -
请注意
[Warning] initialization from incompatible pointer type实际上几乎总是错误而不是警告。 -
它可能应该是
knot_t *current = *start;,因为start是指向knot_t的指针,它来自main()中的addToTheEnd(&start, i),您需要取消引用它才能到达main的start变量的值。 -
你也解决了
if (start == NULL)的问题吗?
标签: c struct linked-list singly-linked-list implicit-conversion