t15BStructuresFunctionsAndArrays

# t15BStructuresFunctionsAndArrays - Structures Functions and...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Structures Functions and Arrays Dale Roberts www.kite-legends.blogspot.com Using Structures With Functions Passing structures to functions Pass entire structure or pass individual members Both pass call by value 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 and returning a pointer from function. and To pass structures call-by-reference To Pass its address Pass Pass reference to it To pass arrays call-by-value Create a structure with the array as a member Create Pass the structure Pass Dale Roberts www.kite-legends.blogspot.com Using Structures With Functions (cont.) (cont.) Using Example: day_of_year(struct date *pd) { int i, day, leap; int day = pd -> day; day leap = pd->year%4 ==0 && pd->year %100 ==0 || pd->year%400 ==0; leap for (i=1; i < pd -> month; i++) for day += day_tab[leap][i]; return (day); return } The declaration struct date *pd; The struct says that pd is a pointer to a structure of the type date says pd pointer date If p is a pointer to a structure, then p-> member_of_structure refers to the If p-> particular members, like pd -> year pd p-> member_of_structure is equivalent to (*p).member_of_structure (*p).member_of_structure Notice: ‘.’ has higher precedence than ‘*’; *pd.year is wrong, since pd.year ‘.’ has ‘*’ is is not a pointer. is Both -> and . associate from left to right. So p -> q -> member -> left So -> are (p->q)->member. are Example: emp.birthday.month are (emp.birthday).month Example (emp.birthday).month Dale Roberts www.kite-legends.blogspot.com Using Structures With Functions (cont.) (cont.) Using -> and . both are at the highest precedence (together with () for () function and for array subscripts) Example: struct { int *x; int int *y; int } *p; is equivalent to ++(p->x) /* increment x, not p */ is */ /* increment p before access x */ /* /* fetch whatever y points to */ /* /* increments y after accessing whatever y point to */ /* /* increments whatever y point to, just like *p->y++ */ /* /* increments p after accessing whatever y point to */ ++p->x; (++p)->x; *p->y; *p->y++; (*p->y)++; *p++->y; Dale Roberts www.kite-legends.blogspot.com typedef typedef Creates synonyms (aliases) for previously defined data types Creates Use typedef to create shorter type names Use typedef Example: typedef struct card *CardPtr; Defines a new type name CardPtr as a synonym for type struct card * Defines CardPtr struct typedef does not create a new data type while it only creates an alias typedef Example: 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) { .. .. } Dale Roberts www.kite-legends.blogspot.com Array of Structures Example: (before) char name[PERSON][NAMESIZE]; int tscore[PERSON] int math[PERSON] int english[PERSON] struct person_data{ .. .. .. .. } person={ {“Jane”,180,89,91}, {“Jane”,180,89,91}, {“John”,190,90,100}, {“John”,190,90,100}, .. .. .. .. .. }; /* similar to 2D array */ similar (now) ⇒ struct person_data{ char name[NAMESIZE]; int tscore; int math; int english; } person[PERSON]; Initialization of structure array the inner brace is not necessary ⇒ “Jane”,180,89,91, “John”,190,90,100, .. .. .. .. Example: using separated arrays average (int tscore, int math, int average eng, int n) eng, { int i, total=0,mathtotal = 0, int engtotal=0; engtotal=0; for (i=0; i<n, i++) { total += *tscore++; mathtotal += *math++; engtotal += *eng++; } 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++; } Dale Roberts www.kite-legends.blogspot.com Unions union Memory that contains a variety of objects over time Only contains one data member at a time Members of a union share space Members union Conserves storage Only the last data member defined can be accessed Same as struct union declarations union Number { int x; int float y; float }; union Number value; Valid union operations Valid union Assignment to union of same type: = Assignment union Taking address: & Taking Accessing union members: . Accessing Accessing members using pointers: -> Accessing -> Dale Roberts www.kite-legends.blogspot.com 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 /* Fig. 10.5: fig10_05.c An example of a union */ #include <stdio.h> union number { int x; double y; }; int main() { union number value; value.x = 100; printf( "%s\n%s\n%s%d\n%s%f\n\n", "Put a value in the integer member", "and print both members.", "int: ", value.x, "double:\n", value.y ); value.y = 100.0; printf( "%s\n%s\n%s%d\n%s%f\n", "Put a value in the floating member", "and print both members.", "int: ", value.x, "double:\n", value.y ); return 0; } Define union Initialize variables Set variables Print Program Output Put a value in the integer member and print both members. int: 100 double: 9255959211743313600000000000000000000000000 0000000000000000000.00000 Put a value in the floating member and print both members. int: 0 double: 100.000000 Dale Roberts www.kite-legends.blogspot.com Bit Fields Bit field Bit Member of a structure whose size (in bits) has been specified Member Enable better memory utilization Enable Must be declared as int or unsigned int unsigned Cannot access individual bits Declaring bit fields Declaring Follow unsigned or int member with a colon (:) and an integer constant representing unsigned int and the width of the field the Example: struct BitCard { unsigned face : 4; unsigned unsigned suit : 2; unsigned unsigned color : 1; unsigned }; Unnamed bit field Field used as padding in the structure Nothing may be stored in the bits Unnamed 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; } Dale Roberts www.kite-legends.blogspot.com Enumeration Constants Enumeration Set of integer constants represented by identifiers Enumeration constants are like symbolic constants whose values are Enumeration automatically set automatically Values start at 0 and are incremented by 1 Values Values can be set explicitly with = Values Need unique constant names Example: enum Months { JAN = enum AUG, 1, FEB, MAR, APR, MAY, JUN, JUL, SEP, OCT, NOV, DEC}; Creates a new type enum Months in which the identifiers are set to the integers 1 to 12 integers Enumeration variables can only assume their enumeration constant Enumeration values (not the integer representations) values Dale Roberts www.kite-legends.blogspot.com 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 /* Fig. 10.18: fig10_18.c Using an enumeration type */ #include <stdio.h> enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; int main() { enum months month; const char *monthName = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for ( month = JAN; month <= DEC; month++ ) printf( "%2d%11s\n", month, monthName[ month ] ); return 0; 1 2 3 4 5 6 7 8 9 10 11 12 January February March April May June July August September October November December 21 } Dale Roberts www.kite-legends.blogspot.com Storage Management C supports 4 functions, malloc(), supports calloc(),free(), and cfree() for storage calloc(),free(), management management malloc(n): malloc(n): allocate a node while its content is still ‘garbage’ n is an integer, indicating the size of memory in byte which you would like to allocate to malloc() return a character pointer to that memory So, you have to use cast operator (type), to change the type of the So, (type) to pointer. pointer. Example: int *ip; int ip = (int*) malloc(sizeof(int)); struct treeNode *tp; tp = (struct tnode *) malloc(sizeof(struct tnode)); Dale Roberts www.kite-legends.blogspot.com Storage Management (cont.) (cont.) Storage free(p): free(p): free() will release the memory allocated by malloc(). free() p is the pointer containing the address returning from malloc(). is Example: */ */ Example: int *ip; int ip = (int*) malloc(sizeof(int)); ip ... .. .. ... free(ip); /* Question: can you free(ip) after ip++ ? /* Question: struct treeNode *tp; struct tp=(struct treeNode *)malloc(sizeof(struct treeNode )); tp=(struct ... .. .. ... free(tp); When there is no further memory, malloc() will return NULL pointer. It is a When malloc() good idea to check the returning value of malloc(). malloc(). if ((ip=(int *)malloc(sizeof(int))) == NULL){ printf(“\nMemory is FULL\n”); exit(1); } When you free the memory, you must be sure that you pass the original When address returning from malloc() to function free(). Otherwise, system address exception may be happened exception Dale Roberts www.kite-legends.blogspot.com Storage Management (cont.) (cont.) Storage calloc(n,size): calloc(n,size): calloc() allow you to allocate an n elements array of same data type. calloc() Because n can be an integer variable, you can use calloc() to allocate a calloc() dynamic size array. dynamic n is the element number of array that you want to allocate. is size is the number of byte of each element. size Unlike malloc(), calloc() guarantees that memory contents are all zero Unlike malloc() calloc() Example: allocate an array of 10 elements int *ip; ip = (int*) calloc(10, sizeof(int)); *(ip+1) refer to the 2nd element, the same as ip[1] refer *(ip+i) refer to the i+1th element, the same as ip[i] refer Like malloc(), calloc() will return NULL, if no further memory is available. Like will cfree(p): cfree() releases the memory allocated by calloc(). releases Example: cfree(ip); Dale Roberts www.kite-legends.blogspot.com ...
View Full Document

## This note was uploaded on 12/08/2010 for the course CSE 2017 taught by Professor Kittu during the Spring '10 term at APIIT.

Ask a homework question - tutors are online