{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# 14 - Lecture 14| More About Structures Revision Structures...

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: Lecture 14| More About Structures Revision: Structures Accessing struct Members with Pointer An Example | struct members and scanf() Structures Containing Array Members Structure Assignments Array of Structures Example | Sorting Structures Nested Structures malloc() and free() Dynamic Array Allocation Readings Exercises CSC 1500 { Lecture 14 1 Overview Structure types usually operate with pointers. A pointer may point to the whole structure variable or just one of its members, depending on the type and usage of the pointer. Structure members can be accessed using the pointer to member operator `->'. Array members of a structure are treated di erently in whole structure assignment. Sorting an array of structures requires special attention to the comparison and swapping operations. CSC 1500 { Lecture 14 2 Revision: Structures #include <stdio.h> typedef enum {MON, TUE, WED, THU, FRI, SAT, SUN} DayType typedef struct { int day int month int year DayType dayOfTheWeek } DateType int main(void) { DateType today today.year today.month today.day today.dayOfTheWeek ... } = = = = 2000 11 3 WED The structure type allows the programmer to aggregate related variables into a single, named variable. These components are called members, which are individually named and accessed. Structure members are accessed using the member operator '.'. Structure variables can be de ned just like variables of simple data types, as follows: DateType today today day month year dayOfTheWeek CSC 1500 { Lecture 14 3 Accessing struct Members with Pointer #include <stdio.h> typedef struct { int day int month int year } DateType int main(void) { DateType DateType int today *date_ptr *ptr ptr = &today.day *ptr = 25 today.month = 12 today.year = 1997 date_ptr = &today (*date_ptr).year = 2000 return 0 } ptr is an today.day *ptr . int pointer. It points (stores the address of) is the dereference of ptr, i.e. referring to today.day. is a DateType pointer. It points (stores the address of) today. date ptr *date ptr today . is the dereference of date ptr , i.e. referring to CSC 1500 { Lecture 14 4 An Example | #include <stdio.h> typedef struct { int day int month int year } DateType struct members and scanf() int main(void) { DateType today DateType *ptr ptr = &today printf("day? ") scanf("%d", &today.day) printf("month? ") scanf("%d", &today.month) printf("year? ") scanf("%d", &today.year) if ((*ptr).day == 25 && ptr->month == 12) printf("\nMerry X'mas!\n") return 0 } day? 25 month? 12 year? 97 Merry X'mas! The precedence of the '.' operator is higher than that of the '&' operator. ptr->month is equivalent to (*ptr).month. CSC 1500 { Lecture 14 5 Structures Containing Array Members #include <stdio.h> #include <string.h> #define NAMEMAX 30 typedef enum {FEMALE, MALE} Gender struct person { char surname NAMEMAX+1] char forename NAMEMAX+1] Gender sex int age } int main(void) { struct person struct person ... } user computer = {"Machine", "Computing", FEMALE, 50} Entities computer computer.surname computer.surname 0] computer.forename 15] computer.age Meaning a structure variable a string variable the 1st character of string computer.surname the 16th character of computer.forename an integer variable CSC 1500 { Lecture 14 6 Structures Containing Array Members #include <stdio.h> #include <string.h> #define NAMEMAX 30 typedef enum {FEMALE, MALE} Gender struct person { char surname NAMEMAX+1] char forename NAMEMAX+1] Gender sex int age } int main(void) { struct person struct person user computer = {"Machine", "Computing", FEMALE, 50} printf("Your surname? ") gets(user.surname) printf("Your forename? ") gets(user.forename) printf("Dear %c. %s\n", user.forename 0], user.surname) printf("I am %c. %s\n", computer.forename 0], computer.surname) return 0 } Your Your Dear I am surname? Collins forename? Phil P. Collins C. Machine CSC 1500 { Lecture 14 7 Structure Assignments #include <stdio.h> #include <string.h> #define NAMEMAX 30 typedef enum {FEMALE, MALE} Gender struct person { char char Gender int } surname NAMEMAX+1] forename NAMEMAX+1] sex age int main(void) { struct person struct person computer1 = {"Machine", "Computing", FEMALE, 50} computer2 /* struct assignment */ computer2 = computer1 printf("computer 1: %s %s\n", computer1.forename, computer1.surname) printf("computer 2: %s %s\n", computer2.forename, computer2.surname) return 0 } computer 1: Computing Machine computer 2: Computing Machine The assignment operator '=' can be applied to struct variables. Individual member of the source struct is copied to the corresponding member of the destination struct. This applies to array members of a structure too. CSC 1500 { Lecture 14 8 Array of Structures A structure may occur as an array element. Example: struct student { char id 9] char name 30] int mark } int main(void) { struct student ... } stulist 100] id name mark id name mark id name mark id name mark ...... id name mark stulist[0] stulist[1] stulist[2] stulist[3] stulist[99] Entities stulist stulist 1] stulist i].name stulist i].name j] Meaning an array of struct student the 2nd element of stulist array a variable of type struct student the name of the (i + 1)th student in the stulist array a string the (j + 1)th character of the name of the (i +1)th student in the stulist array a single character 9 CSC 1500 { Lecture 14 Example | Sorting Structures Sorting means to re-arrange a list of items so that they appear in increasing (or decreasing) order. Given a structure with several members, we have to choose a primary key for sorting. The primary key is the member ( eld) which is used to determine the order of the structures. Example: struct student { char id 9] char name 30] int mark } int main(void) { struct student ... } stulist 100] We may sort the student list according to ascending/descending order of either the id, name or mark. CSC 1500 { Lecture 14 10 Example | Sorting Structures #include <stdio.h> #include <string.h> typedef struct { char id 8 + 1] char name 30 + 1] int mark } StudentRecordType /* sort a list of records according to descending order of the mark member */ void bubble_sort_struct(StudentRecordType a ], int size) { int i, j StudentRecordType temp /* note the type of temp */ for (i=0 i < size-1 i++) /* perform (size-1) rounds */ for (j=size-1 j>i j--) /* starting from the end of the array */ if (a j-1].mark < a j].mark) { /* compare two adjacent records */ temp = a j-1] /* swap the structures in order in case */ a j-1] = a j] /* note that array members are copied too */ a j] = temp } } int main(void) { /* initialize the array of structure */ StudentRecordType stulist 4] = { {"99123456", "Michael Fung", 96}, {"98765432", "Peter Pan", 30}, {"77777777", "Tommy Tang", 100}, {"16249846", "Keung Lee", 999} } int i bubble_sort_struct(stulist, 4) for (i = 0 i < 4 i++) printf(" %s] %-30s %d\n", stulist i].id, stulist i].name, stulist i].mark) return 0 } CSC 1500 { Lecture 14 11 Nested Structures #include <stdio.h> #include <string.h> struct date { int int int } day month year struct book { char char char int struct date } int main(void) { struct book author 30] title 50] publisher 30] edition date_of_pub abook, booklist 100] abook.date_of_pub.day = 10 abook.date_of_pub.month = 2 abook.date_of_pub.year = 1997 strcpy(booklist 10].author, "Al Kelly") strcpy(booklist 10].title, "C By Dissection") strcpy(booklist 10].publisher, "Addison-Wesley") booklist 10].edition = 3 booklist 10].date_of_pub.day = 1 booklist 10].date_of_pub.month = 2 booklist 10].date_of_pub.year = 1996 return 0 } CSC 1500 { Lecture 14 12 malloc() and free() #include <stdio.h> #include <stdlib.h> int main(void) { int i int *p = &i *p = 8 /* declares malloc() and free() */ /* i is an existing variable */ /* p stores the address of i */ /* manipulate i through the pointer p indirectly */ /* get an "un-named" piece of storage */ p = malloc(sizeof(int)) /* p stores the address of the new locker */ *p = i * i printf("The un-named storage holds %d\n", *p) /* release the space pointed by p */ free(p) /* address stored in p is no longer valid */ return 0 } The un-named storage holds 64 malloc() allocates an un-named piece of storage of the requested size. The starting address of the allocated storage is returned and should normally be kept with a suitable pointer variable for further usage and disposal. free() is the counter-part of malloc(). Supplying it with an address of an allocated memory piece, it releases (unregisters) that block of storage and make it no longer valid for further use. This technique is known as Dynamic Memory Allocation. CSC 1500 { Lecture 14 13 Dynamic Array Allocation #include <stdio.h> #include <stdlib.h> int main(void) { int *p, *q /* get an "un-named" piece of storage */ p = malloc(10 * sizeof(int)) /* p stores the starting address of the new block */ q=p *q = 1 q++ *q = 4 p 5] = 9 p 9] = 8 /* make a copy of the address */ /* declares malloc() and free() */ /* release the space pointed by p */ free(p) /* addresses stored in p and q are no longer valid */ return 0 } 120 124 128 132 136 140 144 148 152 156 +---+---+---+---+---+---+---+---+---+---+ |1|4|?|?|?|9|?|?|?|8| +---+---+---+---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 7 8 9 p = 120 initially q = 120 too after the address duplication may be used to allocated a consecutive number storages at once. The total size is required. The storage allocated is uninitialized. The whole block must be freed at once, with the starting address of the rst byte. malloc() CSC 1500 { Lecture 14 14 Readings Chapter 9, Section 9.6 Chapter 12, Sections 12.1 { 12.7 Exercises Chapter 12, Exercises 1, 3, 6, 7, 8, 9, 10 2 End of Lecture 14 CSC 1500 { Lecture 14 15 ...
View Full Document

{[ snackBarMessage ]}