Sie sind auf Seite 1von 14

Dale Roberts

Department of Computer and Information Science, Department of Computer and Information Science,
SchooI of Science, IUPUI SchooI of Science, IUPUI
CSCI 230
Structures
Functions and Arrays
Dale Roberts, Lecturer
Computer Science, IUPUI
E-mail: drobertscs.iupui.edu
Dale Roberts
Using Structures With Functions Using Structures With Functions
Passing structures to functions Passing structures to functions
Pass entire structure or pass individual members Pass entire structure or pass individual members
Both pass call by value Both pass call by value
t is not a good idea to pass a structure to or return from function. t is not a good idea to pass a structure to or return from function.
The better way is passing a pointer to the structure to the functions The better way is passing a pointer to the structure to the functions
and returning a pointer from function. and returning a pointer from function.
%o pass structures caII %o pass structures caII- -by by- -reference reference
Pass its address Pass its address
Pass reference to it Pass reference to it
%o pass arrays caII %o pass arrays caII- -by by- -vaIue vaIue
Create a structure with the array as a member Create a structure with the array as a member
Pass the structure Pass the structure
Dale Roberts
Using Structures With Functions Using Structures With Functions (cont.) (cont.)
ExampIe ExampIe: :
day_of_year(struct date pd) day_of_year(struct date pd)
, ,
int i, day, leap; int i, day, leap;
day = pd day = pd - - day; day;
leap = pd leap = pd- -year%4 ==0 && pd year%4 ==0 && pd- -year %100 ==0 || pd year %100 ==0 || pd- -year%400 ==0; year%400 ==0;
for (i=1; i < pd for (i=1; i < pd - - month; i++) month; i++)
day += day_tab[leap][i]; day += day_tab[leap][i];
return (day); return (day);
, ,
The declaration The declaration 8truct date *pd; 8truct date *pd;
says that says that pd pd is a is a pointer pointer to a structure of the type to a structure of the type date date
f f p p is a pointer to a structure, then is a pointer to a structure, then p p- -> member_of_8tructure > member_of_8tructure refers to the refers to the
particular members, like particular members, like pd pd - -> year > year
p p- -> member_of_8tructure > member_of_8tructure is equivalent to is equivalent to (*p).member_of_8tructure (*p).member_of_8tructure
Notice: Notice: `.' `.' has higher precedence than has higher precedence than `*' `*';; *pd.year *pd.year is wrong, since is wrong, since pd.year pd.year
is not a pointer. is not a pointer.
Both Both - -> > and and . . associate from associate from 01t to right 01t to right. So . So p p - -> q > q - -> member > member
are are (p (p- ->q) >q)- ->member. >member.
Example Example:: emp.birthday.month emp.birthday.month are are (emp.birthday).month (emp.birthday).month
Dale Roberts
Using Structures With Functions Using Structures With Functions (cont.) (cont.)
- - and and . . both are at the highest precedence (together with both are at the highest precedence (together with () () for for
function and function and , , for array subscripts) for array subscripts)
Example Example::
8truct { 8truct {
int *x; int *x;
int *y; int *y;
} *p; } *p;
++p ++p- -x; x; is equivaIent to is equivaIent to ++(p ++(p- -x) / x) / increment increment x, x, not not p / p /
(++p) (++p)- -x; x; /* increment p before access x */ /* increment p before access x */
p p- -y; y; /* fetch whatever y points to */ /* fetch whatever y points to */
p p- -y++; y++; /* increments y after accessing whatever y point to */ /* increments y after accessing whatever y point to */
(p (p- -y)++; y)++; /* increments whatever y point to, just Iike *p /* increments whatever y point to, just Iike *p- ->y++ */ >y++ */
p++ p++- -y; y; /* increments p after accessing whatever y point to */ /* increments p after accessing whatever y point to */
Dale Roberts
typedef typedef
typedef typedef
Creates synonyms (aliases) for previously defined data types Creates synonyms (aliases) for previously defined data types
Use Use typedef typedef to create shorter type names to create shorter type names
Example: Example:
typedef 8truct card *CardPtr; typedef 8truct card *CardPtr;
Defines a new type name Defines a new type name CardPtr CardPtr as a synonym for type as a synonym for type 8truct card * 8truct card *
typedef typedef does not create a new data type while it o does not create a new data type while it only creates an alias nly creates an alias
ExampIe ExampIe: :
8truct card {
con8t char *face;
con8t char *8uit;
};
typedef 8truct card Card;
void fillDeck( Card * con8t, con8t char *[], con8t char *[] );
int main()
{
Card deck[ 52 ];
con8t char *face[] = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
Seven", "Eight", Nine", "Ten", "Jack", "Queen", "King"};
con8t char *8uit[] = { "Heart8", "Diamond8", "Club8", "Spade8"};
.. ..
fillDeck( deck, face, 8uit );
.. ..
}
void fillDeck(Card * con8t wDeck, con8t char * wFace[], con8t char * wSuit[])
{
.. ..
}
Dale Roberts
rray of Structures rray of Structures
ExampIe ExampIe: (before) : (before)
char name[PERSON][NAMESIZE]; char name[PERSON][NAMESIZE];
int t8core[PERSON] int t8core[PERSON]
int math[PERSON] int math[PERSON]
int engli8h[PERSON] int engli8h[PERSON]
nitialization of structure array nitialization of structure array
8truct per8on_data{ 8truct per8on_data{
.. .. .. .. .. .. .. ..
} per8on[]={ } per8on[]={
{Jane,180,89,91}, {Jane,180,89,91},
{John,190,90,100}, {John,190,90,100},
.. .. .. .. .. .. .. ..
}; /* }; /* similar to 2D array similar to 2D array */ */
ExampIe ExampIe: using separated arrays : using separated arrays
average (int tscore, int math, int average (int tscore, int math, int
eng, int n) eng, int n)
, ,
int i, total=0,mathtotal = 0, int i, total=0,mathtotal = 0,
engtotal=0; engtotal=0;
for (i=0; i<n, i++) { for (i=0; i<n, i++) {
total += *t8core++; total += *t8core++;
mathtotal += *math++; mathtotal += *math++;
engtotal += *eng++; engtotal += *eng++;
} }
8truct per8on_data{
char name[NAMESIZE];
int t8core;
int math;
int engli8h;
} per8on[PERSON];
(now)

Example: using pointer to structure


average (8truct per8on_data
*per8on, int n)
{
int i, total=0,mathtotal = 0,
engtotal=0;
for (i=0; i<n, i++) {
total += per8on->t8core;
mathtotal += per8on->math;
engtotal += per8on->eng;
per8on++;
}
the inner brace is not necessary
Jane,180,89,91,
John,190,90,100,
.. .. .. ..

Dale Roberts
Unions Unions
union union
emory that contains a variety of objects over time emory that contains a variety of objects over time
Only contains one data member at a time Only contains one data member at a time
embers of a embers of a union union share space share space
Conserves storage Conserves storage
Only the last data member defined can be accessed Only the last data member defined can be accessed
union union decIarations decIarations
Same as struct Same as struct
union Number { union Number {
int x; int x;
float y; float y;
}; };
union Number value; union Number value;
'aIid 'aIid union union operations operations
ssignment to ssignment to union union of same type: of same type: = =
Taking address: Taking address: & &
ccessing union members: ccessing union members: . .
ccessing members using pointers: ccessing members using pointers: - -> >
Dale Roberts
1 /* Fig. 10.5: fig10_05.c
2 An example of a union */
3 #include <8tdio.h>
4
5 union number {
6 int x;
7 double y;
8 };
9
10 int main()
11 {
12 union number value;
13
14 value.x = 100;
15 printf( "%8n%8n%8%dn%8%fnn",
16 "Put a value in the integer member",
17 "and print both member8.",
18 "int: ", value.x,
19 "double:n", value.y );
20
21 value.y = 100.0;
22 printf( "%8n%8n%8%dn%8%fn",
23 "Put a value in the floating member",
24 "and print both member8.",
25 "int: ", value.x,
26 "double:n", value.y );
27 return 0;
28 }
Put a value in the integer member
and print both member8.
int: 100
double:
-
9255959211743313600000000000000000000000000
0000000000000000000.00000
Put a value in the floating member
and print both member8.
int: 0
double:
100.000000
Define union
nitialize variables
Set variables
Print
Program Output
Dale Roberts
it FieIds it FieIds
it fieId it fieId
ember of a structure whose size (in bits) has been specified ember of a structure whose size (in bits) has been specified
Enable better memory utilization Enable better memory utilization
ust be declared as ust be declared as int int or or un8igned un8igned
Cannot access individual bits Cannot access individual bits
DecIaring bit fieIds DecIaring bit fieIds
ollow ollow un8igned un8igned or or int int member with a colon ( member with a colon (: :) and an integer constant representing ) and an integer constant representing
the width of the field the width of the field
Example Example::
8truct BitCard { 8truct BitCard {
un8igned face : 4; un8igned face : 4;
un8igned 8uit : 2; un8igned 8uit : 2;
un8igned color : 1; un8igned color : 1;
}; };
Unnamed bit fieId Unnamed bit fieId
ield used as padding in the structure ield used as padding in the structure
Nothing may be stored in the bits Nothing may be stored in the bits
Unnamed bit field with zero width aligns next bit field to a new storage unit boundary Unnamed bit field with zero width aligns next bit field to a new storage unit boundary
8truct Example {
un8igned a : 13;
un8igned : 3;
un8igned b : 4;
}
Dale Roberts
Enumeration Constants Enumeration Constants
Enumeration Enumeration
Set of integer constants represented by identifiers Set of integer constants represented by identifiers
Enumeration constants are like symbolic constants whose values are Enumeration constants are like symbolic constants whose values are
automatically set automatically set
Values start at Values start at 0 0 and are incremented by and are incremented by 1 1
Values can be set explicitly with Values can be set explicitly with = =
Need unique constant names Need unique constant names
Example Example::
enum Month8 { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, enum Month8 { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL,
AUG, SEP, OCT, NOV, DEC}; AUG, SEP, OCT, NOV, DEC};
Creates a new type enum onths in which the identifiers are set to the Creates a new type enum onths in which the identifiers are set to the
integers 1 to 12 integers 1 to 12
Enumeration variables can only assume their enumeration constant Enumeration variables can only assume their enumeration constant
values (not the integer representations) values (not the integer representations)
Dale Roberts
1 /* Fig. 10.18: fig10_18.c
2 U8ing an enumeration type */
3 #include <8tdio.h>
4
5 enum month8 { JAN = 1, FEB, MAR, APR, MAY, JUN,
6 JUL, AUG, SEP, OCT, NOV, DEC };
7
8 int main()
9 {
10 enum month8 month;
11 con8t char *monthName[] = { "", "January", "February",
12 "March", "April", "May",
13 "June", "July", "Augu8t",
14 "September", "October",
15 "November", "December" };
16
17 for ( month = JAN; month <= DEC; month++ )
18 printf( "%2d%118n", month, monthName[ month ] );
19
20 return 0;
21 }
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 Augu8t
9 September
10 October
11 November
12 December
Dale Roberts
Storage Management Storage Management
C supports 4 functions, C supports 4 functions, malloc(), calloc(),free(), malloc(), calloc(),free(),
and cfree() and cfree() for storage management for storage management
malloc(n): malloc(n):
allocate a node while its content is still 'garbage' allocate a node while its content is still 'garbage'
n n is an integer, indicating the size of memory in byte which you would like is an integer, indicating the size of memory in byte which you would like
to allocate to allocate
malloc() malloc() return a character pointer to that memory return a character pointer to that memory
So, you have to use cast operator So, you have to use cast operator (type) (type), to change the type of the , to change the type of the
pointer. pointer.
Example Example: :
int *ip; int *ip;
ip = (int*) malloc(8izeof(int)); ip = (int*) malloc(8izeof(int));
8truct treeNode *tp; 8truct treeNode *tp;
tp = (8truct tnode *) malloc(8izeof(8truct tnode)); tp = (8truct tnode *) malloc(8izeof(8truct tnode));
Dale Roberts
Storage Management Storage Management (cont.) (cont.)
free(p): free(p):
free() free() will release the memory allocated by will release the memory allocated by malloc(). malloc().
p p is the pointer containing the address returning from is the pointer containing the address returning from malloc(). malloc().
Example Example::
int *ip; int *ip;
ip = (int*) malloc(8izeof(int)); ip = (int*) malloc(8izeof(int));
... .. .. ... .. ..
free(ip); free(ip); /* /* Question: can you Question: can you free(ip) free(ip) after after ip++ ? */ ip++ ? */
Example Example::
8truct treeNode *tp; 8truct treeNode *tp;
tp=(8truct treeNode *)malloc(8izeof(8truct treeNode )); tp=(8truct treeNode *)malloc(8izeof(8truct treeNode ));
... .. .. ... .. ..
free(tp); free(tp);
When there is no further memory, When there is no further memory, malloc() malloc() will return will return NULL NULL pointer. t is a pointer. t is a
good idea to check the returning value of good idea to check the returning value of malloc(). malloc().
if ((ip=(int *)malloc(8izeof(int))) == NULL){ if ((ip=(int *)malloc(8izeof(int))) == NULL){
printf( printf( nMemory i8 FULL nMemory i8 FULL n); n);
exit(1); exit(1);
} }
When you free the memory, you must be sure that you pass the original When you free the memory, you must be sure that you pass the original
address returning from address returning from malloc() malloc() to function to function free(). free(). Otherwise, system Otherwise, system
exception may be happened exception may be happened
Dale Roberts
Storage Management Storage Management (cont.) (cont.)
calloc(n,size): calloc(n,size):
calloc() calloc() allow you to allocate an allow you to allocate an n n elements array of same data type. elements array of same data type.
Because Because n n can be an integer variable, you can use can be an integer variable, you can use calloc() calloc() to allocate a to allocate a
dynamic size array. dynamic size array.
n n is the element number of array that you want to allocate. is the element number of array that you want to allocate.
8ize 8ize is the number of byte of each element. is the number of byte of each element.
Unlike Unlike malloc() malloc(), , calloc() calloc() guarantees that memory contents are all zero guarantees that memory contents are all zero
Example Example: allocate an array of 10 elements : allocate an array of 10 elements
int *ip; int *ip;
ip = (int*) calloc(10, 8izeof(int)); ip = (int*) calloc(10, 8izeof(int));
*(ip+1) *(ip+1) refer to the 2 refer to the 2
nd nd
element, the same as element, the same as ip[1] ip[1]
*(ip+i) *(ip+i) refer to the i+1 refer to the i+1
th th
element, the same as element, the same as ip[i] ip[i]
Like Like malloc(), calloc() malloc(), calloc() will return will return NULL NULL, if no further memory is available. , if no further memory is available.
cfree(p): cfree(p):
cfree() cfree() releases the memory allocated by releases the memory allocated by calloc() calloc()..
Example Example::
cfree(ip); cfree(ip);

Das könnte Ihnen auch gefallen