35
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)

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)

Embed Size (px)

Citation preview

S09: Structures

Required: PM: Ch 11.1,4, pgs 205-226PM: Ch 11.5, pgs 227-229

Recommended: K&R, Chapter 6Pointer Tutorial (Chps 5,9)

BYU CS 124 Pointers and Arrays 2

CS 224

Chapter Project HomeworkS00: Introduction

Unit 1: Digital Logic

S01: Data TypesS02: Digital Logic

L01: Warm-upL02: FSM

HW01HW02

Unit 2: ISA

S03: ISAS04: MicroarchitectureS05: Stacks / InterruptsS06: Assembly

L03: BlinkyL04: MicroarchL05b: Traffic LightL06a: Morse Code

HW03HW04HW05HW06

Unit 3: C

S07: C LanguageS08: PointersS09: StructsS10: I/O

L07b: Morse IIL08a: LifeL09a: Pong

HW07HW08HW09HW10

Structs 3BYU CS 224

Learning Objectives…

enum typedef’s Structures structs in structs Array of structs struct Pointers Dynamic Memory Allocation Linked List union Bit fields

Structs 4BYU CS 224

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

Structs 5BYU CS 224

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 <type> <name>;

typedef’s

Structs 6BYU CS 224

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;

Structs 7BYU CS 224

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 charactersint altitude; // in meters

int longitude; // in tenths of degrees

int latitude; // in tenths of degreesint heading; // in tenths of degreesdouble airSpeed; // in km/hr

};

Structure definition does not allocate memory.

Structures

Structs 8BYU CS 224

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.altitude 0x000c(SP)plane.longitude 0x000e(SP)plane.latitude 0x0010(SP)plane.heading 0x0012(SP)plane.airspeed 0x0014(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;

Structs 9BYU CS 224

Structure Example

#include <stdio.h>#include <string.h>

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

Structs 10BYU CS 224

Structures in Structures

One field of a struct can be another structurestruct 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

Structs 11BYU CS 224

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 degreesint heading; // in tenths of degreesdouble 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

Structs 12BYU CS 224

Pointers and Structures

As a data type, pointer variables can point to structuresstruct 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

Structs 13BYU CS 224

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

Structs 14BYU CS 224

Memory Usage + Heaps

Variable memory is allocated in three areas:

Global data section Run-time stack Dynamically allocated - heap

0xffffInterrupt Vectors

SFR’s0x0000

Program(Flash)

PC

0x8000

Dynamic Memory Allocation

Global Data Section0x0100

Global variables are allocated in the global data section and are accessible after declaration.

SP Run-time stack0x0600

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

Structs 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 224

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 determineshow much space is necessary

for allocation.

Structs 16BYU CS 224

Dynamic Memory Allocation

#include <stdio.h>#include <stdlib.h>

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 returnedfrom malloc() means it failed

and you are likely out of memory.

Dynamic allocation can be asource of bugs in C code.

Memory leak - allocating memoryand forgetting to free it during

program execution.

Structs 17BYU CS 224

Pointers, Structures, & malloc()

Common to let malloc() create space for structuresstruct 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

Structs 18BYU CS 224

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;

Structs 19BYU CS 224

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 50 75 99 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.

Structs 20BYU CS 224

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

Structs 21BYU CS 224

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 NULLmyList

Linked List

Structs 22BYU CS 224

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 NULLmyList

Linked List

Structs 23BYU CS 224

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 < oldList->value) // prepend element { element->next = oldList; return element; } temp = oldList; while ((temp->next != NULL) && (temp->next->value < element->value)) temp = temp->next; element->next = temp->next; temp->next = element; return oldList;} // end insert

Linked List

Structs 24BYU CS 224

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 NULLmyList 3 65 97 300

Linked List

Structs 25BYU CS 224

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

Structs 26BYU CS 224

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

union{ char c; int i; float f;} x;

x.c = 'z';x.i = 5180;x.f = 3.14;

0ci

1

f

2 3

Structs 27BYU CS 224

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;

time15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

hours minutes seconds

Structs 28

time

BYU CS 224

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;

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

*link

day hour

minute

high low

Structs 29BYU CS 224

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

Structs 30BYU CS 224

// create a new entrySetting* 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 NodeTemperatures

Structs 31BYU CS 224

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

28222c

1e961ea31e31

00000266025e

Temperatures

Structs 32BYU CS 224

Setting* insertSetting(Setting* setting, Setting* oldList){ Setting* temp = oldList; if (oldList == NULL) return setting; // oldList is empty

if (setting->date.time < oldList->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 SettingTemperatures

Structs 33BYU CS 224

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 SettingTemperatures

Structs 34BYU CS 224

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 TestTemperatures

Structs 35BYU CS 224