这里有一些粗略代码可以帮助您入门,我很懒惰并且忽略了释放分配的 FOOD 内存。
通过示例进行跟踪时,我学得最好。我鼓励您密切注意指针显示的值(各种 printfs 中的 %p)。例如,name="Cherries" qty=8 cost=1.23 next=0xa22070 中的 next=0xa22070 来自哪里?
随着您为各种数据结构(链表、树、队列)编写更高级的代码,指针和内存管理将变得越来越重要。
祝你学习曲线顺利:-)
输出
$ gcc food.c
$ ./a.out
--- directly calling print_food() ---
FOOD addr=0xa22010 name="Apple" qty=12 cost=23.90 next=(nil)
FOOD addr=0xa22070 name="Bananas" qty=4 cost=12.90 next=0xa22010
FOOD addr=0xa220d0 name="Cherries" qty=8 cost=1.23 next=0xa22070
--- calling print_food_list() ---
food list #001: FOOD addr=0xa220d0 name="Cherries" qty=8 cost=1.23 next=0xa22070
food list #002: FOOD addr=0xa22070 name="Bananas" qty=4 cost=12.90 next=0xa22010
food list #003: FOOD addr=0xa22010 name="Apple" qty=12 cost=23.90 next=(nil)
Done, n=3
$
food.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUF 64
typedef struct food
{
char name[BUF];
int quantity;
float cost;
struct food *next; // ptr to next food, otherwise null.
} FOOD;
FOOD *make_food(char *name, int quantity, float cost, FOOD *next) {
FOOD *p = malloc(sizeof(FOOD));
strcpy( p->name, name);
p->quantity = quantity;
p->cost = cost;
p->next = next;
return p;
}
void print_food(FOOD *p) {
printf("FOOD addr=%p name=\"%s\" qty=%d cost=%.2f next=%p\n",
p, p->name, p->quantity, p->cost, p->next);
}
int print_food_list(FOOD *p) {
int length = 0;
while( p ) {
++length;
printf("food list #%03d: ", length); // note lack of \n
print_food(p);
p = p->next;
}
return length;
}
void main(int argc, char** argv) {
FOOD *a = make_food( "Apple", 12, 23.90, (FOOD *)NULL );
FOOD *b = make_food( "Bananas", 4, 12.90, a);
FOOD *c = make_food( "Cherries", 8, 1.23, b);
printf("--- directly calling print_food() ---\n");
print_food(a);
print_food(b);
print_food(c);
printf("--- calling print_food_list() ---\n");
int n = print_food_list(c);
// int n = print_food_list(a); // what would happen with a?
printf("Done, n=%d\n", n);
}