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)

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Incomplete Structs struct B; struct A { struct B * partner; // other declarations… }; struct B { struct A * partner; // other declarations… };
Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
Singly Linked List BTECH, EE KAZIRANGA UNIVERSITY.
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Chapter 16 - Pointers and Structures. BYU CS/ECEn 124Structures2 Pointers What is the difference sptr and ssptr? char* sptr[ ] = { "One", "Two", "Three"
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Programming Languages and Paradigms The C Programming Language.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
CP104 Introduction to Programming Structure II Lecture 32 __ 1 Data Type planet_t and Basic Operations Abstract Data Type (ADT) is a data type combined.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Mark Hennessy CS351 Dept Computer Science NUI Maynooth 1 Types CS351 – Programming Paradigms.
Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure.
CS1061 C Programming Lecture 4: Indentifiers and Integers A.O’Riordan, 2004.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CS Data Structures Chapter 4 Lists.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CMPE13 Cyrus Bazeghi Chapter 19 Data Structures. CMPE Data Structures A data structure is a particular organization of data in memory. –We want.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Introduction to Data Structures Systems Programming.
1 Homework HW6 due class 22 K&R 6.6 K&R 5.7 – 5.9 (skipped earlier) Finishing up K&R Chapter 6.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Pointers OVERVIEW.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Introduction to Data Structures Systems Programming Concepts.
Week 4 - Monday.  What did we talk about last time?  Queues  Implementing queues with circular arrays.
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
Week 10 - Wednesday.  What did we talk about last time?  Linked list implementations  Started doubly linked lists.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
 Data Type is a basic classification which identifies different types of data.  Data Types helps in: › Determining the possible values of a variable.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
1 Binghamton University Exam 1 Review CS Binghamton University Birds eye view -- Topics Information Representation Bit-level manipulations Integer.
Stack and Heap Memory Stack resident variables include:
Chapter 6 – Data Types CSCE 343.
Chapter 19 Data Structures
Chapter 19 Data Structures
CSE 374 Programming Concepts & Tools
Instructor: Ioannis A. Vetsikas
Introduction to Data Structures
Chapter 19 Data Structures
Chapter 19 Data Structures
C Structures, Unions, Bit Manipulations and Enumerations
CS 240 – Lecture 18 Command-line Arguments, Typedef, Union, Bit Fields, Pointers to Functions.
Pointers, Dynamic Data, and Reference Types
C Language B. DHIVYA 17PCA140 II MCA.
Module 13 Dynamic Memory.
Chapter 19 Data Structures -struct -dynamic memory allocation
Presentation transcript:

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

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

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

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 };

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

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;

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

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;

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 = ; strcpy(fred.name, "Flintstone, Fred"); fred.ssn = ; 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

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 = ; tom.weight = 150; tom.address.zipCode = 84062; } initials ssn height weight address street city zipCode person structs in structs

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

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 = ; printf(“%s %ld\n”, (*rubble).name, (*rubble).ssn); } strcpy(rubble->name, “Rubble, Barney”); rubble->ssn = ; printf(“%s %ld\n”, rubble->name, rubble->ssn); Not Common More Common How Much Memory? struct Pointers

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", , 74, NULL, NULL }; struct person bill = { "wj", , 75, NULL, NULL }; struct person susan = { "sd", , 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

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

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.

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.

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 = ; 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

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;

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

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 NULL Linked List void printList(Element* ptr) {while (ptr != NULL) {lcd_printf(" %d", ptr->value); ptr = ptr->next; } lcd_printf("\n"); } Pattern Factory

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); } NULL myList Linked List

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); } NULL myList Linked List

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

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 Linked List

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

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

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 hoursminutesseconds

time BYU CS 224Structs28 Quiz 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; *link dayhourminute highlow

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

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

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 026e e28 222c 1e961ea31e e Temperatures

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

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

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

BYU CS 224Structs35