Professional Documents
Culture Documents
: (structures)
:
( , )
,
035 . . . .
5-1
:
(struct)
.
(,
, )
035 . . . .
5-2
struct
:
typedef struct
{
1;
2;
...
;
} ;
035 . . . .
5-3
,
:
:
typedef
struct{
char
name[30];
char
addr[20];
char
phone[15];
int
age;
}
Person;
(
double char)
person name,
addr ... person
035 . . . .
5-4
struct
#include<stdio.h>
typedef struct
{
char name[30];
char addr[20];
char phone[15];
int age;
} Person;
main()
{
int k, m; // oi k,m int
Person principle, student1, student2;
// principle, student1, student2
// person
}
: sizeof(person) 66 (30+20+12+4)
035 . . . .
5-5
, .
#include<stdio.h>
#include<string.h>
typedef struct{
char name[30];
char addr[20];
char phone[12];
int age;
} Person;
main()
{
Person myperson;
myperson.age=30;
strcpy(myperson.name,Dimitris);
printf(%d\n, myperson.age);
}
035 . . . .
5-6
Person x1, x2;
:
.. x1 == x2 .
.. x1.age == x2.age
035 . . . .
5-7
&
typedef struct
{
int x;
int y;
char name[10];
} Point;
5, 3, PointA
int main()
Same point
{
Press any key to continue . . .
Point a,b;
strcpy(a.name,"PointA");
a.x=5;
a.y=3;
b=a; // a b
printf("%d, %d, %s\n",b.x,b.y,b.name);
if (a.x==b.x && a.y==b.y && strcmp(a.name,b.name)==0)// a==b
printf("Same point\n");
system("PAUSE");
return 0;
}
035 . . . .
5-8
,
struct _ [];
..
typedef struct
{
int x;
int y;
char name[10];
} Point;
main()
{
Point a[100]; // 100 struct point
a[73].x=10;
strcpy(a[5].name,Z);
}
035 . . . .
5-9
typedef struct
{
char name[20];
int age;
} Person;
int main()
{
int i;
Person friends[10];
for (i=0;i<3;i++)
{
printf("Give name: ");
Kostas -> 27
gets(friends[i].name);
Mary -> 24
printf("Give age: ");
Dimitris -> 30
scanf("%d",&friends[i].age);
Press any key to continue . . .
fflush(stdin);//
}
// \n
printf("\n");
//input stream
for (i=0;i<3;i++)
printf("%s -> %d\n",friends[i].name,friends[i].age);
system("PAUSE");
return 0;
}
035 . . . .
5-10
:
(int, char, float)
..
typedef struct {
char firstName[15];
int age;
} Person;
typedef struct {
Person father;
Person mother;
int numofchild;
Person children[5];
} Family;
int main(void){
Person x, y, z;
Family fml;
x.age = 25;
fml.numofchild = 2;
fml.father.age = 50;
strcpy(fml.father.firstName, Joe);
}
035 . . . .
5-11
.
:
Person inc_age (Person x){
x.age += 1;
return x;
}
main(){
Person x1, x2;
x2 = inc_age(x1);
}
( x
)
035 . . . .
5-12
.
Person *pp, p;
pp
Person .
pp = &p;
printf(%d, (*pp).age);
*pp ,
(*pp).name .
: , .,
, *.
(*pp).name .
*pp.age=5 compile error
035 . . . .
5-13
()
()
. -> (struct)
!
* / %
+ < <= >= >
== !=
&&
||
=
035 . . . .
5-14
:
(*p)._
=
p->_
.
( &).
Person p;
...
initPerson(&p);
...
void initPerson(Person *p){
strcpy( p->firstName, A);
strcpy( p->lastName, );
p->gender = M;
p->age = 43;
Person *p;
( *p [malloc])
.
initPerson(p);
...
void initPerson(Person *p){
strcpy( p->firstName, A);
strcpy( p->lastName, );
p->gender = M;
p->age = 43;
}
}
035 . . . .
5-15