C语言链表:动态内存分配和释放示例
// 在程序结束前释放动态分配的内存 free(a); free(b); free(c);
#include <stdio.h> #include <stdlib.h>
struct student { int num; char name[20]; double score; struct student *next; };
int main() { struct student *a, *b, c, p, head = NULL; a = (struct student)malloc(sizeof(struct student)); b = (struct student)malloc(sizeof(struct student)); c = (struct student)malloc(sizeof(struct student));
scanf("%d%s%lf", &a->num, a->name, &a->score); scanf("%d%s%lf", &b->num, b->name, &b->score); scanf("%d%s%lf", &c->num, c->name, &c->score);
head = a; a->next = b; b->next = c; c->next = NULL;
p = head; printf("%d,%s,%.2f\n", p->num, p->name, p->score); p = p->next; printf("%d,%s,%.2f\n", p->num, p->name, p->score);
// 释放内存 free(a); free(b); free(c);
return 0; }
原文地址: https://www.cveoy.top/t/topic/oil2 著作权归作者所有。请勿转载和采集!