Presentation is loading. Please wait.

Presentation is loading. Please wait.

S09: Structures Required: PM: Ch 11.1,4, pgs 205-226 PM: Ch 11.5, pgs 227-229 Recommended: K&R, Chapter 6 Pointer Tutorial (Chps 5,9)

Similar presentations


Presentation on theme: "S09: Structures Required: PM: Ch 11.1,4, pgs 205-226 PM: Ch 11.5, pgs 227-229 Recommended: K&R, Chapter 6 Pointer Tutorial (Chps 5,9)"— Presentation transcript:

1 S09: Structures Required: PM: Ch 11.1,4, pgs 205-226 PM: Ch 11.5, pgs 227-229 Recommended: K&R, Chapter 6 Pointer Tutorial (Chps 5,9)

2 BYU CS 124Pointers and Arrays2 CS 224 ChapterProjectHomework S00: Introduction Unit 1: Digital Logic S01: Data Types S02: Digital Logic L01: Warm-up L02: FSM HW01 HW02 Unit 2: ISA S03: ISA S04: Microarchitecture S05: Stacks / Interrupts S06: Assembly L03: Blinky L04: Microarch L05b: Traffic Light L06a: Morse Code HW03 HW04 HW05 HW06 Unit 3: C S07: C Language S08: Pointers S09: Structs S10: I/O L07b: Morse II L08a: Life L09a: Pong HW07 HW08 HW09 HW10

3 BYU CS 224Structs3 Learning Objectives… enum typedef’s Structures structs in structs Array of structs struct Pointers Dynamic Memory Allocation Linked List union Bit fields

4 BYU CS 224Structs4 Enum Enums in C are a way to map identifiers to integral values (thus avoiding magic numbers in your code). The advantage of enum over #define is that it has scope. Only visible within the block it was declared. Easier to change values – let the compiler do the work. Two types of enum’s: Named: enum greekType { ALPHA, BETA, GAMMA }; Unnamed: enum { HOMER, MARGE, BART, LISA }; Values start at zero, unless specified. enum enum { zero, one, two, three }; enum animals { cat=1, dog, cow=9, sheep, goat }; enum plants { grass, roses, cabbages, oaktree }; enum BOOLEAN { FALSE, TRUE };

5 BYU CS 224Structs5 Why typedef? We use variables with logical names - why not use data types with logical names? What’s an "int"? 8-bits, 16-bits, 32-bits? What’s a “long”? Better question: why memorize it? Most data types are platform dependent! typedef’s introduce synonyms for types which could have been declared some other way. typedef’s make your code more portable. typedef’s usually declared in single.h file. Syntax: typedef ; typedef’s

6 BYU CS 224Structs6 Why typedef? How to use typedef’s: 1)Create a logical data type scheme. 2)Create a “typedef.h” file for each microcontroller platform you use. 3)#include "typedef.h" in each of your files. 4)Use the new data type names. typedef’s typedef signed char int8; typedef unsigned char uint8; typedef signed short int16; typedef unsigned short uint16; typedef signed long int32; typedef unsigned long uint32; Replace: unsigned char variable; with: uint8 variable;

7 BYU CS 224Structs7 Structures A structure is a collection of variables, possibly of different types, grouped together under a single name (tag). Help organize complicated data. Must be defined prior to a structure variable being declared. Definitions include a tag, member elements, and a variable definition. struct flightType { char flightNum[6];// max 6 characters int altitude;// in meters int longitude;// in tenths of degrees int latitude;// in tenths of degrees int heading;// in tenths of degrees double airSpeed;// in km/hr }; Structure definition does not allocate memory. Structures

8 BYU CS 224Structs8 Structures Memory for a struct is allocated when a variable is declared using the new structure definition type: struct flightType plane; plane.flightNum[0]0x0000(SP) plane.flightNum[1]0x0002(SP) plane.flightNum[2]0x0004(SP) plane.flightNum[3]0x0006(SP) plane.flightNum[4]0x0008(SP) plane.flightNum[5]0x000a(SP) plane.altitude0x000c(SP) plane.longitude0x000e(SP) plane.latitude0x0010(SP) plane.heading0x0012(SP) plane.airspeed0x0014(SP) Structures Structure members are laid out in the order specified by the definition. Members of an allocated struct can be accessed with the “dot” operator: plane.altitude = 10000; plane.heading = 800;

9 BYU CS 224Structs9 Structure Example #include struct person { char name[32]; long ssn; }; struct person barney, fred; int main() { strcpy(barney.name, "Rubble, Barney"); barney.ssn = 555234561; strcpy(fred.name, "Flintstone, Fred"); fred.ssn = 123451234; printf(“\n%s %ld", fred.name, fred.ssn); printf(“\n%s %ld", barney.name, barney.ssn); } Does not allocate memory Allocates two global memory structs Structures

10 BYU CS 224Structs10 Structures in Structures One field of a struct can be another structure struct addressStruct {char street[32]; char city[16]; long zipCode; }; struct person {char initials[4]; long ssn; int height; int weight; struct addressStruct address; } tom; int main() {tom.ssn = 555123456; tom.weight = 150; tom.address.zipCode = 84062; } initials ssn height weight address street city zipCode person structs in structs

11 BYU CS 224Structs11 Arrays of Structures struct's are data types and hence an array of struct's makes sense: typedef struct flightType {char flightNum[6];// max 6 characters int altitude;// in meters int longitude;// in tenths of degrees int latitude;// in tenths of degrees int heading;// in tenths of degrees double airSpeed;// in km/hr } Flight planes[100]; Each array element is a structure. To access a member of a particular element in the array, used array index and the “.” dot operator: planes[34].altitude = 10000; Array of structs

12 BYU CS 224Structs12 Pointers and Structures As a data type, pointer variables can point to structures struct person {char name[32]; long ssn; } barney, *rubble; int main() { rubble = &barney; strcpy((*rubble).name, “Rubble, Barney”); (*rubble).ssn = 555234561; printf(“%s %ld\n”, (*rubble).name, (*rubble).ssn); } strcpy(rubble->name, “Rubble, Barney”); rubble->ssn = 555234561; printf(“%s %ld\n”, rubble->name, rubble->ssn); Not Common More Common How Much Memory? struct Pointers

13 BYU CS 224Structs13 Pointers and Structures Since pointers can point to structures, then it’s easy to make links between structures. struct person {char initials[2]; long ssn; int height; struct person *father; struct person *mother; }; /* Declare variables and initialize them at the same time */ struct person tom = { "tj", 555235512, 74, NULL, NULL }; struct person bill = { "wj", 351003232, 75, NULL, NULL }; struct person susan = { "sd", 980332153, 70, NULL, NULL }; int main() {/* Set tom's parents pointers */ tom.father = &bill; tom.mother = &susan; printf(“\nTom's mother's height is: %d in", tom.mother->height); } tom susan mother bill father tom is a struct and mother is a field in that struct, thus tom.mother is correct. mother is a pointer to a struct and thus mother- >height is correct. Combine them for tom.mother->height struct Pointers

14 BYU CS 224Structs14 Memory Usage + Heaps Variable memory is allocated in three areas: Global data section Run-time stack Dynamically allocated - heap 0xffff Interrupt Vectors SFR’s 0x0000 Program (Flash) PC 0x8000 Dynamic Memory Allocation Global Data Section 0x0100 Global variables are allocated in the global data section and are accessible after declaration. SP Run-time stack 0x0600 Local variables are allocated during execution on the stack. Heap Dynamically allocated variables are allocated memory at run-time from the heap. malloc() – allocates memory free() – frees memory

15 Dynamic memory allocation using malloc() is used for many kinds of programs. When data size is unknown or variable. Building abstract structures like trees and linked lists. BYU CS 224Structs15 Dynamic Memory Allocation int main() {int *dynArray; double *ddynArray; /* Allocate space for 16 ints */ dynArray = (int *)malloc( 16 * sizeof(int) ); dynArray[6] = 65; dynArray[12] = 2; /* Allocate space for 20 doubles */ ddynArray = (double *)malloc( 20 * sizeof(double) ); } Dynamic Memory Allocation The sizeof() function determines how much space is necessary for allocation.

16 BYU CS 224Structs16 Dynamic Memory Allocation #include main() { int *dynArray; /* Allocate space for 16 ints */ dynArray = (int *)malloc( 16 * sizeof(int) ); if (dynArray != NULL) { dynArray[6] = 65; dynArray[12] = 2; doSomething( dynArray ); free( dynArray ); } Dynamic Memory Allocation A NULL pointer returned from malloc() means it failed and you are likely out of memory. Dynamic allocation can be a source of bugs in C code. Memory leak - allocating memory and forgetting to free it during program execution.

17 BYU CS 224Structs17 Pointers, Structures, & malloc() Common to let malloc() create space for structures struct person {char initials[2]; long ssn; int height; struct person *father; struct person *mother; } *tom, *bill, *susan; int main() {tom = (struct person *)malloc( sizeof( struct person ) ); bill = (struct person *)malloc( sizeof( struct person ) ); susan = (struct person *)malloc( sizeof( struct person ) ); strncpy(tom->initials, "tj“, 2); tom->ssn = 555235512; tom->father = bill; tom->mother = susan; susan->height = 68; /* Since tom is now a pointer, tom->mother->height is correct. */ printf(“\nTom's mother's height is: %d", tom->mother->height); } Dynamic Memory Allocation

18 BYU CS 224Structs18 Quiz 9.1 1)How is an int passed to a function? 2)How is a char array passed to a function? 3)How is an auto struct passed to a function? 4)How is a malloc’d struct passed to a function? 5)How many bytes of the heap is removed by a function call to malloc(4) ? How many returned? 6)How much memory is allocated for fred? barney? struct person {uint8* name[2]; uint32 ssn; } fred, *barney;

19 BYU CS 224Structs19 Linked List Data Structure A linked list is an collection of nodes, each of which contains data and is connected using pointers. Each node points to the next node in the list. The first node in the list is called the head. The last node in the list is called the tail. list 507599 NULL Linked List Advantages of a linked list - Dynamic size. Easy to add/remove nodes. Advantages of an array - Easy to quickly access arbitrary elements.

20 BYU CS 224Structs20 typedef struct element {int value; struct element* next; } Element; Element* newElement(int value) {Element* temp; temp = (Element*)malloc( sizeof(Element) ); temp->value = value; temp->next = NULL; return temp; } int main() {/* Create linked list */ Element *list = NULL; list = newElement(50); list->next = newElement(75); list->next->next = newElement(99); printList(list); } Example 9.1 list 50 75 99 NULL Linked List void printList(Element* ptr) {while (ptr != NULL) {lcd_printf(" %d", ptr->value); ptr = ptr->next; } lcd_printf("\n"); } Pattern Factory

21 BYU CS 224Structs21 Pre-pend Node // Prepend element to oldList, return ptr to new list ----- Element* prepend(Element* element, Element* oldList) { element->next = oldList; return element; // return ptr to new head } // end prepend int main() { Element* myList = newElement(45); myList = prepend(newElement(30), myList); myList = prepend(newElement(10), myList); printList(myList); } 10 30 45 NULL myList Linked List

22 BYU CS 224Structs22 Append Node // --- Append element to oldList, return ptr to list --- Element* append(Element* element, Element* oldList) { Element* temp = oldList; if (oldList == NULL) return element; // empty list while (temp->next != NULL) temp = temp->next; // find end temp->next = element; return oldList; } // end append int main() { Element* myList = append(newElement(200), myList); myList = append(newElement(201), myList); myList = append(newElement(202), myList); printList(myList); } 200 201 202 NULL myList Linked List

23 BYU CS 224Structs23 Insert Node // Insert element into oldList, return ptr to list ---- Element* insert(Element* element, Element* oldList) { Element* temp; if (oldList == NULL) return element; // new list if (element->value value) // prepend element { element->next = oldList; return element; } temp = oldList; while ((temp->next != NULL) && (temp->next->value value)) temp = temp->next; element->next = temp->next; temp->next = element; return oldList; } // end insert Linked List

24 BYU CS 224Structs24 Insert Node int main() { Element *myList = NULL; RBX430_init(_12MHZ); // init board lcd_init(); // init LCD lcd_clear(); // clear LCD // Insert some items into list myList = insert(newElement(65), myList); myList = insert(newElement(2), myList); myList = insert(newElement(97), myList); myList = insert(newElement(3), myList); myList = insert(newElement(300), myList); printList(myList); } // end main 2 NULL myList 36597300 Linked List

25 BYU CS 224Structs25 Free Node Elements in a linked list need to be “freed” or you will have a memory leak. When “freeing” items in a linked list, be careful not to “saw off the limb you’re standing on”. void freeList(Element* list) { if (list == NULL) return; freeList(list->next); free(list); // free end node } int main() { freeList(myList); // free linked list } Linked List

26 BYU CS 224Structs26 Union A union is a value that may have any of several representations or formats. Unions are defined like structures (structs), except that each data member begins at the same location in memory. The union object occupies as much space as the largest member. Unions are similar to "variant records" in other languages. union { char c; int i; float f; } x; x.c = 'z'; x.i = 5180; x.f = 3.14; 0 c i 1 f 23

27 BYU CS 224Structs27 Bit Fields Specify bit-sized objects within structs or unions. Bit fields do not have addresses—you can't have pointers to them or arrays of them. Be careful using them. Require run-time code to manipulate - could end up using more space than they save. No guarantee of the ordering of fields within machine words, so programs will be non-portable and compiler-dependent. Bit Fields typedef struct { unsigned short hour:5; unsigned short min:6; unsigned short sec:5; } Time time; time 1514131211109876543210 hoursminutesseconds

28 time BYU CS 224Structs28 Quiz 9.2 1.How many bytes are allocated for mySetting? 2.How do you set hours in mySetting to 12? typedef struct Setting_struct { struct Setting_struct* link; union { uint16 time; struct { uint8 day:3; uint8 hour:5; uint8 minute; } times; } date; uint8 high; uint8 low; } Setting mySetting; 1514131211109876543210 *link dayhourminute highlow

29 BYU CS 224Structs29 Example 9.2 Thermostat temperature entry: Temperatures link date high low typedef unsigned int uint16; typedef unsigned char uint8; enum {SUN=0, MON, TUE, WED, THUR, FRI, SAT}; typedef struct Setting_struct { struct Setting_struct* link; union { uint16 time; // day:hour/minute struct { uint8 day:3; // day of week (0-6) uint8 hour:5; // hour (0-23) uint8 minute; // minute (0-59) } times; } date; uint8 high; uint8 low; } Setting; NULL

30 BYU CS 224Structs30 // create a new entry Setting* newSetting(uint8 day, uint8 hour, uint8 minute, uint8 high, uint8 low) { // malloc a new node Setting* temp = (Setting*)malloc(sizeof(Setting)); // store entries temp->date.times.day = day; temp->date.times.hour = hour; temp->date.times.minute = minute; temp->high = high; temp->low = low; // null link temp->link = NULL; return temp; } // end newSetting Create New Node Temperatures

31 BYU CS 224Structs31 int main() { Setting *list = NULL; // Create linked list list = newSetting(MON, 6, 30, 22<<1, 20<<1); list->link = newSetting(WED, 20, 30, 17<<1, 15<<1); list->link->link = newSetting(FRI, 8, 30, 22<<1, 20<<1); list->link->link->link = newSetting(SAT, 18, 30, 20<<1, 18<<1); } main 28 2c 1e45 026e0256 241e28 222c 1e961ea31e31 00000266025e Temperatures

32 BYU CS 224Structs32 Setting* insertSetting(Setting* setting, Setting* oldList) { Setting* temp = oldList; if (oldList == NULL) return setting; // oldList is empty if (setting->date.time date.time) { setting->link = oldList; // pre-pend setting return setting; } while (temp->link != NULL) // Search for location { if (temp->date.time == setting->date.time) { temp->high = setting->high; // replace setting temp->low = setting->low; free(setting); return oldList; } if (temp->link->date.time > setting->date.time) break; temp = temp->link; // next } setting->link = temp->link; // insert setting temp->link = setting; return oldList; } // end insertSetting Insert Setting Temperatures

33 BYU CS 224Structs33 const char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; void printList(Setting* ptr) { while (ptr != NULL) { lcd_printf("\n%s %02d:%02d %4.1f-%4.1f", days[ptr->date.times.day], ptr->date.times.hour, ptr->date.times.minute, (float)ptr->high / 2.0, (float)ptr->low / 2.0 ); ptr = ptr->link; } lcd_printf("\n"); } // end printList Print Setting Temperatures

34 BYU CS 224Structs34 void main(void) { Setting *list = NULL; RBX430_init(_1MHZ);// init board lcd_init();// init LCD lcd_clear(0); // Create linked list list = newSetting(MON, 6, 30, 22<<1, 20<<1); list->link = newSetting(WED, 20, 30, 17<<1, 15<<1); list->link->link = newSetting(FRI, 8, 30, 22<<1, 20<<1); list->link->link->link = newSetting(SAT, 18, 30, 20<<1, 18<<1); // Insert some items into list list = insertSetting(newSetting(MON, 6, 30, 24<<1, 18<<1), list); list = insertSetting(newSetting(SUN, 6, 30, 22<<1, 20<<1), list); list = insertSetting(newSetting(TUE, 6, 30, 22<<1, 20<<1), list); list = insertSetting(newSetting(MON, 6, 30, 20<<1, 10<<1), list); list = insertSetting(newSetting(SAT, 20, 30, 22<<1, 20<<1), list); printList(list); return; } Final Test Temperatures

35 BYU CS 224Structs35


Download ppt "S09: Structures Required: PM: Ch 11.1,4, pgs 205-226 PM: Ch 11.5, pgs 227-229 Recommended: K&R, Chapter 6 Pointer Tutorial (Chps 5,9)"

Similar presentations


Ads by Google