在下面的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
指向的next
成员内容的成员指针h1
,即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
,如果代码在许多层次上增长很多,会使代码难以理解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句