Department of Computer and Information Science School of







![Memory Layout Example: struct data 1 { int day 1; char month[9]; int year; Memory Layout Example: struct data 1 { int day 1; char month[9]; int year;](https://slidetodoc.com/presentation_image/addb2cf214dcf69a47aad8284d4937a5/image-8.jpg)
![sizeof Operator sizeof(struct tag) struct test { char name[5]; int i; char s; } sizeof Operator sizeof(struct tag) struct test { char name[5]; int i; char s; }](https://slidetodoc.com/presentation_image/addb2cf214dcf69a47aad8284d4937a5/image-9.jpg)






![Array of Structures Example: (before) char name[PERSON][NAMESIZE]; int tscore[PERSON] int math[PERSON] int english[PERSON] struct Array of Structures Example: (before) char name[PERSON][NAMESIZE]; int tscore[PERSON] int math[PERSON] int english[PERSON] struct](https://slidetodoc.com/presentation_image/addb2cf214dcf69a47aad8284d4937a5/image-16.jpg)

![Link list Example: Struct list. Node { char word[SIZE]; int count; struct list. Node Link list Example: Struct list. Node { char word[SIZE]; int count; struct list. Node](https://slidetodoc.com/presentation_image/addb2cf214dcf69a47aad8284d4937a5/image-18.jpg)






- Slides: 24
Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Structures Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs. iupui. edu Dale Roberts
Introduction Structures A collection of one or more variables, possibly of different types, grouped together under a single name for continent handling. Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues, and trees Example: struct card { char *face; char *suit; }; struct introduces the definition for structure card is the structure name and is used to declare variables of the structure type card contains two members of type char * These members are face and suit Dale Roberts
Structure Definitions Example: A date consists of several parts, such as the day, month, and year, and the day of the year, and the month name struct date { int day; int month; int year_date; char month_name[4]; }; date: the name of the structure, called structure tag. day, month, …: the elements or variables mentioned in a structure are called members. struct information A struct cannot contain an instance of itself Can contain a member that is a pointer to the same structure type A structure definition does not reserve space in memory Instead creates a new data type used to declare structure variables Dale Roberts
Declaration of Variables of Structure Declarations method 1: declared like other variables: declare tag first, and then declare variable. struct card { char *face; char *suit; }; struct card one. Card, deck[ 52 ], *c. Ptr; struct date {. . . }; struct date d 1, d 2, d 3, d 4, d 5; method 2: A list of variables can be declared after the right brace and use comma separated list: struct card { char *face; char *suit; } one. Card, deck[ 52 ], *c. Ptr; method 3: Declare only variables. struct { char *face; char *suit; } one. Card, deck[ 52 ], *c. Ptr; Dale Roberts struct date { . . . } d 1, d 2, d 3; struct date d 4, d 5; struct { . . . } d 1, d 2, d 3, d 4, d 5;
Structure Definitions Valid Operations Assigning a structure to a structure of the same type Taking the address (&) of a structure Accessing the members of a structure Using the sizeof operator to determine the size of a structure Initialization of Structures Initializer lists Example: struct card one. Card = { "Three", "Hearts" }; Example: struct date d 1 = {4, 7, 1776, 186, “Jul”}; struct date d 2 = {4, 7, 1776, 186, {‘J’, ’u’, ’l’, ’ ’}}; Assignment statements Example: card three. Hearts = one. Card; Dale Roberts
Accessing Members of Structures Accessing structure members Dot (. ) is a member operator used with structure variables Syntax: structure_name. member struct card my. Card; printf( "%s", my. Card. suit ); One could also declare and initialize three. Hearts as follows: struct card three. Hearts; three. Hearts. face = “Three”; three. Hearts. suit = “Hearts”; Arrow operator (->) used with pointers to structure variables struct card *my. Card. Ptr = &my. Card; printf( "%s", my. Card. Ptr->suit ); my. Card. Ptr->suit is equivalent to (*my. Card. Ptr). suit Dale Roberts
Structures Structure can be nested • Name Rule • Members in different structure can have the same name, since they are at different position. struct date { int day; int month; int year_date; char month_name[4]; }; struct person { char name [NAME_LEN]; char address[ADDR_LEN}; long zipcode; long ss__number; double salary; }; struct date birthday; struct s 1 {. . . . char name[10]; . . . . } d 1; struct s 2 {. . . . int name; . . . . } d 2; struct s 3 {. . . . int name; struct s 2 t 3; . . . . } d 3; float name; struct person emp; emp. birthday. month = 6; emp. birthday. year = 1776; Dale Roberts
Memory Layout Example: struct data 1 { int day 1; char month[9]; int year; }; Word (2 bytes) alignment machine – begins (aligns) at even address, such as PC, SUN workstation day 1 int month char array (hole) year int 2 bytes 9 bytes 1 bytes 2 bytes Quad (4 bytes) address alignment – begins (aligns) at quad address, such as VAX 8200 day 1 month (hole) year int char array int 4 bytes 9 bytes 3 bytes 4 bytes 0 1 2 - 10 integer 9 character 11 (hole) 12 13 integer 0 -3 4 - 12 integer 13 - 15 16 -19 9 character (hole) integer You must take care of hole, if you want to access data from very low level (i. e. low-level I/O, byte operations, etc. ) Dale Roberts
sizeof Operator sizeof(struct tag) struct test { char name[5]; int i; char s; } t 1, t 2; /* assume int is 2 bytes */ main() { printf(“sizeof(struct test) = %dn”, sizeof (struct test)); printf(“address of t 1 = %dn”, &t 1); printf(“address of t 2 = %dn”, &t 2); printf(“address of t 1. name = %dn”, t 1. name); t 1 992 5 bytes printf(“address of t 1. i = %dn”, &t 1. i); 1 byte (hole) 997 printf(“address of t 1. s = %dn”, &t 1. s); 2 bytes } 998 output: t 2 sizeof(struct test) = 10 address of t 1 = 992 address of t 2 = 1002 address of t 1. name = 992 address of t 1. i = 998 address of t 1. s = 1000 1001 1002 1 byte (hole) 5 bytes 1 byte (hole) 2 bytes 1 byte (hole) Dale Roberts
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 and returning a pointer from function. To pass structures call-by-reference Pass its address Pass reference to it To pass arrays call-by-value Create a structure with the array as a member Pass the structure Dale Roberts
Using Structures With Functions (cont. ) Example: day_of_year(struct date *pd) { int i, day, leap; day = pd -> day; leap = pd->year%4 ==0 && pd->year %100 ==0 || pd->year%400 ==0; for (i=1; i<pd -> month; i++) day += day_tab[leap][i]; return (day); } The declaration struct date *pd; says that pd is a pointer to a structure of the type date If p is a pointer to a structure, then p-> member_of_structure refers to the particular members, like pd -> year p-> member_of_structure is equivalent to (*p). member_of_structure Notice: ‘. ’ has higher precedence than ‘*’; *pd. year is wrong, since pd. year is not a pointer. Both -> and. associate from left to right. So p -> q -> member are (p->q)->member. Example: emp. birthday. month are (emp. birthday). month Dale Roberts
Using Structures With Functions (cont. ) -> and. both are at the highest precedence (together with () for function and [] for array subscripts) Example: ++p->x; (++p)->x; *p->y++; (*p->y)++; *p++->y; struct { int *x; int *y; } *p; is equivalent to ++(p->x) /* increment x, not p */ /* 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 */ Dale Roberts
typedef Creates synonyms (aliases) for previously defined data types Use typedef to create shorter type names Example: typedef struct card *Card. Ptr; Defines a new type name Card. Ptr as a synonym for type struct card * typedef does not create a new data type while it only creates an alias Example: struct card { const char *face; const char *suit; }; typedef struct card Card; void fill. Deck( Card * const, 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"}; . . fill. Deck( deck, face, suit ); . . } void fill. Deck(Card * const w. Deck, const char * w. Face[], const char * w. Suit[]) {. . } Dale Roberts
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 Conserves storage Only the last data member defined can be accessed union declarations Same as struct union Number { int x; float y; }; union Number value; Valid union operations Assignment to union of same type: = Taking address: & Accessing union members: . Accessing members using pointers: -> Dale Roberts
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: fig 10_05. c An example of a union */ #include <stdio. h> union number { int x; double y; }; Define union int main() { union number value; Initialize variables Set variables value. x = 100; Print printf( "%sn%s%dn%s%fnn", "Put a value in the integer member", "and print both members. ", Program Output "int: ", value. x, Put a value in the integer member "double: n", value. y ); and print both members. int: 100 value. y = 100. 0; double: printf( "%sn%s%dn%s%fn", "Put a value in the floating member", 925595921174331360000000000000 "and print both members. ", "int: ", value. x, Put a value in the floating member "double: n", value. y ); and print both members. return 0; int: 0 } double: 100. 000000 Dale Roberts
Array of Structures Example: (before) char name[PERSON][NAMESIZE]; int tscore[PERSON] int math[PERSON] int english[PERSON] struct person_data{ char name[NAMESIZE]; int tscore; int math; int english; } person[PERSON]; (now) Initialization of structure array struct person_data{. . . . } person[]={ {“Jane”, 180, 89, 91}, {“John”, 190, 100}, . . . . }; /* similar to 2 D array */ the inner brace is not necessary “Jane”, 180, 89, 91, “John”, 190, 100, . . . . Example: using separated arrays Example: using pointer to structure average (int tscore, int math, int eng, int n) { int i, total=0, mathtotal = 0, engtotal=0; for (i=0; i<n, i++) { total += *tscore++; mathtotal += *math++; engtotal += *eng++; } 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
Self-Reference Structure Dynamic Data Structure: link list, tree, graph, … Example: Binary Tree Struct tree. Node { char word[SIZE]; int count; struct tree. Node *left; struct tree. Node *right; /* or struct tree. Node *left, *right; */ }; /* Inorder traversal */ tree_print(struct tree. Node *p) { if (p!=NULL){ tree_print(p->left); printf(“. . ”, p->word, . . ); tree_print(p-> right); } } Dale Roberts
Link list Example: Struct list. Node { char word[SIZE]; int count; struct list. Node *next; }; /* Inorder traversal */ list_print(struct list. Node *p) { while (p!=NULL) { printf(“. . ”, p->word, . . ); p = p->next; } } Dale Roberts
Bit Fields Bit field Member of a structure whose size (in bits) has been specified Enable better memory utilization Must be declared as int or unsigned Cannot access individual bits Declaring bit fields Follow unsigned or int member with a colon (: ) and an integer constant representing the width of the field Example: struct Bit. Card { unsigned face : 4; unsigned suit : 2; unsigned color : 1; }; Unnamed bit field struct Example { unsigned a : 13; unsigned : 3; unsigned b : 4; } 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 Dale Roberts
Enumeration Constants Enumeration Set of integer constants represented by identifiers Enumeration constants are like symbolic constants whose values are automatically set Values start at 0 and are incremented by 1 Values can be set explicitly with = Need unique constant names Example: enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; Creates a new type enum Months in which the identifiers are set to the integers 1 to 12 Enumeration variables can only assume their enumeration constant values (not the integer representations) Dale Roberts
1 /* Fig. 10. 18: fig 10_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 *month. Name[] = { "", "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( "%2 d%11 sn", month. Name[ month ] ); 19 20 return 0; 21 } Dale Roberts 1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September 10 October 11 November 12 December
Storage Management C supports 4 functions, malloc(), calloc(), free(), and cfree() for storage management 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 malloc() return a character pointer to that memory So, you have to use cast operator (type), to change the type of the pointer. Example: int *ip; ip = (int*) malloc(sizeof(int)); struct tree. Node *tp; tp = (struct tnode *) malloc(sizeof(struct tnode)); Dale Roberts
Storage Management (cont. ) free(p): free() will release the memory allocated by malloc(). p is the pointer containing the address returning from malloc(). Example: int *ip; ip = (int*) malloc(sizeof(int)); . . . . free(ip); /* Question: can you free(ip) after ip++ ? */ Example: struct tree. Node *tp; tp=(struct tree. Node *)malloc(sizeof(struct tree. Node )); . . . . free(tp); When there is no further memory, malloc() will return NULL pointer. It is a good idea to check the returning value of malloc(). if ((ip=(int *)malloc(sizeof(int))) == NULL){ printf(“n. Memory is FULLn”); exit(1); } When you free the memory, you must be sure that you pass the original address returning from malloc() to function free(). Otherwise, system exception may be happened Dale Roberts
Storage Management (cont. ) calloc(n, size): calloc() allow you to allocate an n elements array of same data type. Because n can be an integer variable, you can use calloc() to allocate a dynamic size array. n is the element number of array that you want to allocate. size is the number of byte of each element. Unlike malloc(), calloc() guarantees that memory contents are all zero Example: allocate an array of 10 elements int *ip; ip = (int*) calloc(10, sizeof(int)); *(ip+1) refer to the 2 nd element, the same as ip[1] *(ip+i) refer to the i+1 th element, the same as ip[i] Like malloc(), calloc() will return NULL, if no further memory is available. cfree(p): cfree() releases the memory allocated by calloc(). Example: cfree(ip); Dale Roberts