结构体与共用体03 - 零基础入门学习C语言55
第十章:结构体与共用体03
让编程改变世界
Change the world by program
结构指针变量作函数参数
将一个结构体变量的值传递给另一个函数,有3个方法: (1)用结构体变量的成员作参数 (2)用结构体变量作实参 (3)用指向结构体变量(或数组)的指针作实参,将结构体变量(或数组)的地址传给形参实战例题
例题:有一个结构体变量stu,内含学生学号、姓名和3门课程的成绩。通过调用函数print中将它们输出。 要求: 先用结构体变量作函数参数: [codesyntax lang="c"]#include <stdio.h>
#include <string.h>
struct student
{
int num;
char *name;
float score[3];
};
void print(struct student);
void main()
{
struct student stu;
stu.num = 8;
stu.name = "Fishc.com!";
stu.score[0] = 98.5;
stu.score[1] = 99.0;
stu.score[2] = 99.5;
print( stu );
}
void print( struct student stu )
{
printf("tnum : %dn", stu.num);
printf("tname : %sn", stu.name);
printf("tscore_1 : %5.2fn", stu.score[0]);
printf("tscore_2 : %5.2fn", stu.score[1]);
printf("tscore_3 : %5.2fn", stu.score[2]);
printf("n");
}
[/codesyntax]
改用指向结构体变量的指针作实参: example02.c
[codesyntax lang="c"]
#include <stdio.h>
#include <string.h>
struct student
{
int num;
char name[20];
float score[3];
};
void print(struct student *);
void main()
{
struct student stu;
stu.num = 8;
strcpy(stu.name, "Fishc.com!");
stu.score[0] = 98.5;
stu.score[1] = 99.0;
stu.score[2] = 99.5;
print( &stu );
}
void print( struct student *p )
{
printf("tnum : %dn", p -> num);
printf("tname : %sn", p -> name);
printf("tscore_1 : %5.2fn", p -> score[0]);
printf("tscore_2 : %5.2fn", p -> score[1]);
printf("tscore_3 : %5.2fn", p -> score[2]);
printf("n");
}
[/codesyntax]
动态存储分配
在数组一章中,曾介绍过数组的长度是预先定义好的,在整个程序中固定不变。C语言中不允许动态数组类型。 例如:int a[n]; 用变量表示长度,想对数组的大小作动态说明,这是错误的。 但是在实际的编程中,往往会发生这种情况,即所需的内存空间取决于实际输入的数据,而无法预先确定。 所以对于这种问题,用数组的办法很难解决! 为了解决上述问题,C语言提供了一些内存管理函数,这些内存管理函数可以按需要动态地分配内存空间,也可把不再使用的空间回收待用,为 有效地利用内存资源提供了手段。常用的内存管理函数有以下三个:
1. 分配内存空间函数 malloc、calloc 2. 释放内存空间函数 freemalloc函数
函数原型为 void *malloc(unsigned int size); 其作用是在内存的动态存储区中分配一个长度为size的连续空间(size是一个无符号数)。 此函数的返回值是一个指向分配域起始地址的指针(类型为void)。 如果此函数未能成功地执行(例如内存空间不足),则返回空指针(NULL)。calloc函数
函数原型为 void *calloc (unsigned n, unsigned size); 其作用是在内存的动态存储区中分配n个长度为size的连续空间。 函数返回一个指向分配域起始地址的指针; 如果分配不成功,返回NULL。 用calloc函数可以为一维数组开辟动态存储空间,n为数组元素个数,每个元素长度为size。free函数
函数原型为 void free (void *p); 其作用是释放由p指向的内存区,使这部分内存区能被其他变量使用。 p是最近一次调用calloc或malloc函数时返回的值。 free函数无返回值。链表
什么是链表? 链表是一种常见的重要的数据结构,是动态地进行存储分配的一种结构。链表的组成:
头指针:存放一个地址,该地址指向第一个元素 结点:用户需要的实际数据和链接节点的指针 [caption id="attachment_184" align="aligncenter" width="300"]
链表的组成[/caption]
实践
我们尝试根据下图建立链表: [caption id="attachment_185" align="aligncenter" width="300"]
链表的组成[/caption]
[codesyntax lang="c"]
#include <stdio.h>
struct student
{
long num;
float score;
struct student *next;
};
void main()
{
struct student a, b, c, *head;
a.num = 10101;
a.score = 89.5;
b.num = 10103;
b.score = 90;
c.num = 10107;
c.score = 85;
head = &a;
a.next = &b;
b.next = &c;
c.next = NULL;
do
{
printf("%ld %5.1fn", head->num, head->score);
head = head->next;
}while( head != NULL );
}
[/codesyntax]

浙公网安备 33010602011771号