【发布时间】:2017-12-10 10:16:14
【问题描述】:
所以我试图以非全局形式练习我的 C 双指针链表,我很困惑为什么 s——实际上是 head——首先指向 null 然后是一些随机地址,即使我认为我将它移到了第一个节点在列表中。
这是我的代码:
typedef struct nodeStruct{
int item;
struct nodeStruct *next;
} Statistician;
void add(Statistician **s, int x);
void displayData(Statistician **s);
int main(int argc, char *argv[]) {
Statistician *s = NULL;
add(&s, 3);
add(&s, 4);
add(&s, 5);
add(&s, 6);
add(&s, 7);
add(&s, 8);
add(&s, 9);
displayData(&s);
return 0;
}
void add(Statistician **s, int x){
Statistician *temp = malloc(sizeof(Statistician));
temp->item = x;
temp->next = NULL;
if(s == NULL){
s = &temp;
}
else{
Statistician *travel = s;
while(travel->next!=NULL){
travel = travel->next;
}
travel->next = temp;
}
}
void displayData(Statistician **s){
Statistician *temp = s;
printf("List is: ");
while(temp!=NULL){
printf("%d ", temp->item);
temp = temp->next;
}
}
我从我的代码中得到了这个输出,我也得到了这些警告:
List is: 0 43586480 3 4 5 6 7 8 9
[警告] 从不兼容的指针类型初始化 [默认启用] 在这行代码
统计学家 *travel = s
我总是可以在打印数据之前移动显示数据两次,这样我不想看到的第一个就不会消失,但我想知道它为什么会这样工作。我也可以忽略这些错误,但我想学习如何修复它。
【问题讨论】:
标签: c pointers linked-list singly-linked-list double-pointer