Professional Documents
Culture Documents
บทที่ 8 -8.6
บทที่ 8 -8.6
6 (arrays of structures)
1
10 20 arrays
8.6.1
struct
1
struct struct_name
{
type1 name1;
type2 name2;
..
typeN nameN;
} struct_var[n];
2
struct struct_name
{
type1 name1;
type2 name2;
..
typeN nameN;
};
struct struct_name struct_var[n];
struct
struct_name
struct_var
type1 name1, type2 name2, ., typeN nameN 1, 2, 3, ,
employee[0],, employee[9] ( 8.4 )
name
age
employee[0]
employee[1]
..
employee[9]
25 bytes
4 bytes
25 bytes
4 bytes
25 bytes
4 bytes
salary
2 bytes
2 bytes
..
2 bytes
..
8.4
8.6.2
struct_var[n].member_var
n 0,1, 2, ,n-1
8.4 employee[3].salary 4
8.5 employee[7].name 8
struct_var[n].member_var = value;
strcpy (s2,s1)
employee[0].age = 20;
strcpy(employee[0].name, Kannikar);
8.6
/*
arrstru.c */
#include<stdio.h> /* printf(), getche(), gets() in this file */ /* 1 */
#include<stdlib.h> /* atoi(), atof(), tolower() in this file */ /* 2 */
#include<ctype.h>
/* 4 */
void newname(void); /* functions prototype of newname() */ /* 5 */
void listall(void);
/* functions prototype of listall() */
/* 6 */
struct person
/* 7 */
{
/* 8 */
char name[30];
/* 9 */
int age;
/* 10 */
float salary;
/* 11 */
};
/* 12 */
struct person employee[50]; /* array of 50 structures */ /* 13 */
int n=0;
/* 14 */
void main(void)
/* 15 */
{
/* 16 */
char ch;
/* 17 */
do {
/* 18 */
clrscr( );
/* 19 */
printf(" ****************************\n");
/*
20 */
printf(" * Main Menu *\n");
/* 21 */
printf(" ****************************\n");
/*
22 */
printf(" 1. Create a new employee\n");
/* 23 */
printf(" 2. Display All employees\n");
/* 24 */
printf(" 3. Exit Program\n\n");
/* 25 */
printf(" Enter your choice ( 1 or 2 or 3 ) : ");
/* 26 */
ch=getche();
/* 27 */
switch(tolower(ch))
/* 28 */
{
/* 29 */
case '1':
/* 30 */
newname(); break;
/* 31 */
case '2':
/* 32 */
listall(); break;
/* 33 */
case '3':
/* 34 */
printf("\nExit Program."); exit(0);
/* 35 */
default:
/* 36 */
printf("\n Choice Error ! Please choice agian"); /* 37 */
}
/* 38 */
}while(ch!='3');
/* 39 */
}/* end main */
/* 40 */
/* newname() */
/* 41 */
void newname()
/* 42 */
{
/* 43 */
char numstr[81];
/* 44 */
printf("\n Record %d.\n Enter name:", n+1);
/* 45 */
gets(employee[n].name);
/* 46 */
/* 47 */
/* 48 */
/* 49 */
/* 50 */
/* 51 */
/* 52 */
/* 53 */
/* 54 */
/* 55 */
/* 56 */
/* 57 */
/* 58 */
/* 59 */
/* 60 */
/* 61 */
/* 62 */
/* 63 */
/* 64 */
/* 65 */
/* 66 */