14.4 结构数组
如果处理多本书,可以使用这一类型的结构数组来处理这本书。程序清单14.2就创建了一个这样的数组。
结构和内存
manybook.c程序创建了一个内含100个结构变量的数组。由于该数组是自动存储类别的对象,其中的信息被存储在栈(stack)中。如此大的数组可能需要很大一块内存,这可能会导致一些问题。如果在运行时出现错误,可能抱怨堆栈太小或栈溢出,你的编译器可能使用了一个默认大小的
栈,这个栈对于该例而言太小。要修正这个问题,可以使用编译器选项设置栈大小为10000,以容纳这个结构数组;或者可以创建静态或外部数组(这样,编译器就不会把数组放在栈中);或者可以减小数组大小为16。为何不一开始就使用较小的数组?这是为了让读者意识到栈大小的潜在问题,以便今后再遇到类似的问题,可以自己处理好。
程序清单14.2 manybook.c程序
/* manybook.c -- multiple book inventory */
#include <stdio.h>
#include <string.h>
char * s_gets(char * st, int n);
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 100 /* maximum number of books */
struct book { /* set up book template */
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
int main(void)
{
struct book library[MAXBKS]; /* array of book structures */
int count = 0;
int index;
printf("Please enter the book title.\n");
printf("Press [enter] at the start of a line to stop.\n");
while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL
&& library[count].title[0] != '\0')
{
printf("Now enter the author.\n");
s_gets(library[count].author, MAXAUTL);
printf("Now enter the value.\n");
scanf("%f", &library[count++].value);
while (getchar() != '\n')
continue; /* clear input line */
if (count < MAXBKS)
printf("Enter the next title.\n");
}
if (count > 0)
{
printf("Here is the list of your books:\n");
for (index = 0; index < count; index++)
printf("%s by %s: $%.2f\n", library[index].title,
library[index].author, library[index].value);
}
else
printf("No books? Too bad.\n");
return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
char * find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n'); // look for newline
if (find) // if the address is not NULL,
*find = '\0'; // place a null character there
else
while (getchar() != '\n')
continue; // dispose of rest of line
}
return ret_val;
}
/* 输出:
*/
Borland C和浮点数
如果程序不使用浮点数,旧式的Borland C编译器会尝试使用小版本的scanf()来压缩程序。然而,如果在一个结构数组中只有一个浮点数,那么这种编译器(DOS的Borland C/C++ 3.1之前的版本,不是Borland C/C++ 4.0)就无法发现它存在。结果,编译器会生成如下信息:
scanf : floating point formats not linked
Abnormal program termination
一种解决方案是,在程序中添加下面的代码:
#include <math.h>
double dummy = sin( 0.0 );
这段代码强制编译器载入浮点版本的scanf()。
14.4.1 声明结构数组
声明结构数组和声明其他类型的数组类似。下面是一个声明结构数组的例子:
struct book library[MAXBKS];
以上代码把library声明为一个内含MAXBKS个元素的数组。数组名library本身不是结构名,它是一个数组名,该数组中的每个元素都是struct book类型的结构变量。
14.4.2 表示结构数组的成员
为了标识结构数组中的成员,可以采用访问单独结构的规则:在结构名后面加一个点运算符,再在点运算符后面写上成员名。如下所示:
library[0].value /*第1个数组元素与value相关联*/
注意,数组下标紧跟在library后面,不是成员名后面:
library.value[2] //错误
library[2].value //正确
使用library[2].value的原因是:library[2]是结构变量名。
顺带一提,下面的表达式代表什么?
library[2].title[4]
这是library数组的第3个结构变量(library[2]部分)中书名的第5个字符。
该例指出,点运算符右侧的下标作用于各个成员,点运算符左侧的下标作用于结构数组。
最后,总结一下:
library //一个book结构的数组
library[2] //一个数组元素,该元素是book结构
library[2].title //一个char数组(library[2]的title成员)
library[2].title[4] //数组中library[2]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。