t15bstructuresfunctionsandarrays.pps

14
Dale Roberts Department of Computer and Information Science, Department of Computer and Information Science, School of Science, IUPUI School of Science, IUPUI CSCI 230 Structures Functions and Arrays Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected]

Upload: anjali-naidu

Post on 12-Jul-2016

217 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

Department of Computer and Information Science,Department of Computer and Information Science,School of Science, IUPUISchool of Science, IUPUI

CSCI 230

StructuresFunctions and Arrays

Dale Roberts, LecturerComputer Science, IUPUIE-mail: [email protected]

Page 2: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

Using Structures With FunctionsUsing Structures With Functions

Passing structures to functionsPassing structures to functionsPass entire structure or pass individual membersPass entire structure or pass individual members

Both pass call by valueBoth pass call by value

It is not a good idea to pass a structure to or return from function.It 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.

To pass structures call-by-reference To pass structures call-by-reference Pass its addressPass its address

Pass reference to itPass reference to it

To pass arrays call-by-valueTo pass arrays call-by-valueCreate a structure with the array as a member Create a structure with the array as a member

Pass the structurePass the structure

Page 3: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

Using Structures With Functions Using Structures With Functions (cont.)(cont.)

ExampleExample::day_of_year(struct date *pd)day_of_year(struct date *pd){{ int i, day, leap;int i, day, leap;

day = pd -> day;day = pd -> day; leap = pd->year%4 ==0 && pd->year %100 ==0 || pd->year%400 ==0;leap = pd->year%4 ==0 && pd->year %100 ==0 || pd->year%400 ==0; for (i=1; i < pd -> month; i++)for (i=1; i < pd -> month; i++)

day += day_tab[leap][i];day += day_tab[leap][i]; return (day);return (day);}}

The declaration The declaration struct date *pd;struct date *pd;says that says that pdpd is a is a pointerpointer to a structure of the type to a structure of the type datedateIf If pp is a pointer to a structure, then is a pointer to a structure, then p-> member_of_structurep-> member_of_structure refers to the refers to the particular members, like particular members, like pd -> yearpd -> year p-> member_of_structure p-> member_of_structure is equivalent to is equivalent to (*p).member_of_structure(*p).member_of_structureNotice:Notice: ‘.’‘.’ has higher precedence thanhas higher precedence than ‘*’‘*’;; *pd.year *pd.year is wrong, sinceis wrong, since pd.year pd.year is not a pointer.is not a pointer.BothBoth ->-> and and . . associate from associate from left to rightleft to right. So . So p -> q -> memberp -> q -> memberare are (p->q)->member. (p->q)->member. ExampleExample:: emp.birthday.month emp.birthday.month are are (emp.birthday).month(emp.birthday).month

Page 4: t15BStructuresFunctionsAndArrays.pps

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)

ExampleExample::struct {struct { int *x;int *x; int *y;int *y;} *p;} *p;

++p->x; ++p->x; is equivalent tois equivalent to ++(p->x) /* ++(p->x) /* increment increment x, x, not not p */p */

(++p)->x; (++p)->x; /* increment p before access x *//* increment p before access x */

*p->y; *p->y; /* fetch whatever y points to *//* fetch whatever y points to */

*p->y++; *p->y++; /* increments y after accessing whatever y point to *//* increments y after accessing whatever y point to */

(*p->y)++; (*p->y)++; /* increments whatever y point to, just like *p->y++ *//* increments whatever y point to, just like *p->y++ */

*p++->y; *p++->y; /* increments p after accessing whatever y point to */ /* increments p after accessing whatever y point to */

Page 5: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

typedeftypedef

typedeftypedef Creates synonyms (aliases) for previously defined data typesCreates synonyms (aliases) for previously defined data typesUse Use typedeftypedef to create shorter type names to create shorter type namesExample:Example:

typedef struct card *CardPtr;typedef struct card *CardPtr;Defines a new type name Defines a new type name CardPtrCardPtr as a synonym for type as a synonym for type struct card *struct card *

typedeftypedef does not create a new data type while it o does not create a new data type while it only creates an aliasnly creates an alias

ExampleExample:: struct card { const char *face; const char *suit;};

typedef struct card Card;void fillDeck( Card * const, const char *[], const char *[] );

int main(){ Card deck[ 52 ]; const char *face[] = {"Ace", "Deuce", "Three", "Four", "Five", "Six",

Seven", "Eight", “Nine", "Ten", "Jack", "Queen", "King"}; const char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades"}; .. .. fillDeck( deck, face, suit ); .. ..}

void fillDeck(Card * const wDeck, const char * wFace[], const char * wSuit[]){.. ..}

Page 6: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

Array of StructuresArray of StructuresExampleExample: (before): (before)

char name[PERSON][NAMESIZE];char name[PERSON][NAMESIZE];int tscore[PERSON]int tscore[PERSON]int math[PERSON]int math[PERSON]int english[PERSON]int english[PERSON]

Initialization of structure arrayInitialization of structure arraystruct person_data{struct person_data{

.. .. .. .... .. .. ..} person[]={} person[]={ {“Jane”,180,89,91},{“Jane”,180,89,91}, {“John”,190,90,100},{“John”,190,90,100}, .. .. .. .... .. .. .. }; /* }; /* similar to 2D arraysimilar to 2D array */ */

ExampleExample: 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 += *tscore++;total += *tscore++;mathtotal += *math++;mathtotal += *math++;engtotal += *eng++;engtotal += *eng++;

}}

struct person_data{char name[NAMESIZE];int tscore;int math;int english;

} person[PERSON];

(now)

Example: using pointer to structure

average (struct person_data *person, int n){int i, total=0,mathtotal = 0, engtotal=0;

for (i=0; i<n, i++) {total += person->tscore;mathtotal += person->math;engtotal += person->eng;person++;

}

the inner brace is not necessary

“Jane”,180,89,91,“John”,190,90,100,.. .. .. ..

Page 7: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

UnionsUnions

unionunionMemory that contains a variety of objects over timeMemory that contains a variety of objects over timeOnly contains one data member at a timeOnly contains one data member at a timeMembers of a Members of a unionunion share space share spaceConserves storageConserves storageOnly the last data member defined can be accessedOnly the last data member defined can be accessed

unionunion declarations declarationsSame as structSame as struct

union Number {union Number { int x;int x; float y;float y;};};union Number value;union Number value;

Valid Valid unionunion operations operationsAssignment to Assignment to unionunion of same type: of same type: ==Taking address: Taking address: &&Accessing union members: Accessing union members: ..Accessing members using pointers: Accessing members using pointers: ->->

Page 8: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

1 /* Fig. 10.5: fig10_05.c

2 An example of a union */

3 #include <stdio.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( "%s\n%s\n%s%d\n%s%f\n\n",

16 "Put a value in the integer member",

17 "and print both members.",

18 "int: ", value.x,

19 "double:\n", value.y );

20

21 value.y = 100.0;

22 printf( "%s\n%s\n%s%d\n%s%f\n",

23 "Put a value in the floating member",

24 "and print both members.",

25 "int: ", value.x,

26 "double:\n", value.y );

27 return 0;

28 }

Put a value in the integer memberand print both members.int: 100double:-92559592117433136000000000000000000000000000000000000000000000.00000 Put a value in the floating memberand print both members.int: 0double:100.000000

Define union

Initialize variables

Set variables

Print

Program Output

Page 9: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

Bit FieldsBit Fields

Bit field Bit field Member of a structure whose size (in bits) has been specifiedMember of a structure whose size (in bits) has been specified

Enable better memory utilization Enable better memory utilization

Must be declared as Must be declared as intint or or unsignedunsigned

Cannot access individual bitsCannot access individual bits

Declaring bit fields Declaring bit fields Follow Follow unsignedunsigned or or intint member with a colon ( member with a colon (::) and an integer constant representing ) and an integer constant representing the width of the fieldthe width of the field

ExampleExample::

struct BitCard {struct BitCard { unsigned face : 4;unsigned face : 4; unsigned suit : 2;unsigned suit : 2; unsigned color : 1;unsigned color : 1;};};

Unnamed bit fieldUnnamed bit fieldField used as padding in the structureField used as padding in the structure

Nothing may be stored in the bitsNothing may be stored in the bits

Unnamed bit field with zero width aligns next bit field to a new storage unit boundaryUnnamed bit field with zero width aligns next bit field to a new storage unit boundary

struct Example { unsigned a : 13; unsigned : 3; unsigned b : 4;}

Page 10: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

Enumeration ConstantsEnumeration Constants

EnumerationEnumerationSet of integer constants represented by identifiersSet 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 setautomatically set

Values start at Values start at 00 and are incremented by and are incremented by 11

Values can be set explicitly with Values can be set explicitly with ==

Need unique constant namesNeed unique constant namesExampleExample::

enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; AUG, SEP, OCT, NOV, DEC};

Creates a new type enum Months in which the identifiers are set to the Creates a new type enum Months in which the identifiers are set to the integers 1 to 12integers 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)

Page 11: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

1 /* Fig. 10.18: fig10_18.c

2 Using an enumeration type */

3 #include <stdio.h>

4

5 enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,

6 JUL, AUG, SEP, OCT, NOV, DEC };

7

8 int main()

9 {

10 enum months month;

11 const char *monthName[] = { "", "January", "February",

12 "March", "April", "May",

13 "June", "July", "August",

14 "September", "October",

15 "November", "December" };

16

17 for ( month = JAN; month <= DEC; month++ )

18 printf( "%2d%11s\n", month, monthName[ month ] );

19

20 return 0;

21 }

1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September10 October11 November12 December

Page 12: t15BStructuresFunctionsAndArrays.pps

Dale Roberts

Storage ManagementStorage Management

C supports 4 functions, C supports 4 functions, malloc(), malloc(), calloc(),free(), and cfree()calloc(),free(), and cfree() for storage for storage managementmanagement malloc(n):malloc(n):

allocate a node while its content is still ‘garbage’allocate a node while its content is still ‘garbage’

nn 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 allocateto 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.

ExampleExample: :

int *ip;int *ip;

ip = (int*) malloc(sizeof(int));ip = (int*) malloc(sizeof(int));

struct treeNode *tp;struct treeNode *tp;

tp = (struct tnode *) malloc(sizeof(struct tnode));tp = (struct tnode *) malloc(sizeof(struct tnode));

Page 13: t15BStructuresFunctionsAndArrays.pps

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 fromis the pointer containing the address returning from malloc(). malloc().

ExampleExample:: int *ip;int *ip; ip = (int*) malloc(sizeof(int));ip = (int*) malloc(sizeof(int)); ... .. ..... .. ..

free(ip);free(ip); /* /* Question: can youQuestion: can you free(ip) free(ip) after after ip++ ? */ip++ ? */

ExampleExample:: struct treeNode *tp;struct treeNode *tp; tp=(struct treeNode *)malloc(sizeof(struct treeNode ));tp=(struct treeNode *)malloc(sizeof(struct 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. It is a pointer. It is a good idea to check the returning value of good idea to check the returning value of malloc().malloc().if ((ip=(int *)malloc(sizeof(int))) == NULL){if ((ip=(int *)malloc(sizeof(int))) == NULL){

printf(“\nMemory is FULL\n”);printf(“\nMemory is FULL\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 fromaddress returning from malloc() malloc() to function to function free(). free(). Otherwise, system Otherwise, system exception may be happenedexception may be happened

Page 14: t15BStructuresFunctionsAndArrays.pps

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 nn elements array of same data type. elements array of same data type. Because Because nn 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.

sizesize 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 zeroExampleExample: allocate an array of 10 elements: allocate an array of 10 elements

int *ip;int *ip;

ip = (int*) calloc(10, sizeof(int));ip = (int*) calloc(10, sizeof(int));

*(ip+1) *(ip+1) refer to the 2refer to the 2ndnd element, the same as element, the same as ip[1] ip[1]

*(ip+i) *(ip+i) refer to the i+1refer to the i+1thth element, the same as element, the same as ip[i] ip[i]

Like Like malloc(), calloc() malloc(), calloc() will returnwill 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 byreleases the memory allocated by calloc() calloc()..

ExampleExample::cfree(ip);cfree(ip);