在下面的 C 代码中,我创建了一个链接列表和一个打印成员的 int
值的函数。我在 main
中创建了一些示例成员,但是没有打印任何内容,我不明白为什么。
#include <stdio.h>
#include <stdlib.h>
typedef struct node * ptr;
typedef struct node {
int data;
ptr next;
} item;
void printList(ptr p);
int main() {
item h1 = {12, NULL};
item h2 = {13, h1.next};
item h3 = {14, h2.next};
printList(h3.next);
}
void printList(ptr p) {
while(p) {
printf("%d -> \n", ptr -> data);
ptr = ptr -> next;
}
}
最佳答案
您的初始化错误。
item h2 = {13, h1.next};
初始化h2
next
成员指针,指向h1
的next
成员的内容,即NULL
,与 h3
相同。
#include <stdio.h>
typedef struct node {
int data;
struct node *next;
} item;
void printList(item *p);
int main(void) {
item h1 = {12, NULL};
item h2 = {13, &h1};
item h3 = {14, &h2};
printList(&h3);
}
void printList(item *p) {
while(p) {
printf("%d -> \n", p->data);
p = p->next;
}
}
输出
14 ->
13 ->
12 ->
旁注:
避免使用typedef
隐藏指针,如果代码层数增多,代码会变得难以理解。
关于c - 为什么我无法打印链接列表成员的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41868956/