Chapter 16 - Pointers and Structures - PowerPoint PPT Presentation

1 / 47
About This Presentation
Title:

Chapter 16 - Pointers and Structures

Description:

Chapter 16 - Pointers and Structures – PowerPoint PPT presentation

Number of Views:248
Avg rating:3.0/5.0
Slides: 48
Provided by: PaulR186
Category:

less

Transcript and Presenter's Notes

Title: Chapter 16 - Pointers and Structures


1
Chapter 16 - Pointers and Structures
2
Pointers
  • What is the difference sptr and ssptr?
  • char sptr "One", "Two", "Three"
  • char xsptr sptr

3
Concepts to Learn
  • enum
  • Structures
  • typedefs
  • structs in structs
  • Array of structs
  • struct Pointers
  • Union
  • Bit Fields
  • Dynamic Memory Allocation
  • Linked List

4
enum
enum
  • Closely related to the define preprocessor.
  • Define a list of aliases which represent integer
    numbers.
  • The advantage of enum over define is that it has
    scope.
  • Only visible within the block it was declared.
  • Two types
  • Named enum greekType ALPHA, BETA, GAMMA
  • Unnamed enum HOMER, MARGE, BART, LISA
  • Values start at zero, unless specified.

5
enum Examples
enum
enum numbers zero, one, two, three enum
animals cat1, dog, cow9, sheep, enum
plants grass, roses, cabbages, oaktree enum
diseases heart, skin, brain, circulatory
enum quarks charmed, strange, truth, beauty
enum treasures rubies, sapphires, gold,
silver
6
Structures
Structures
  • A structure is a collection of variables,
    possibly of different types, grouped together
    under a single name (tag).
  • Structures help organize complicated data.
  • A structure must be defined prior to a structure
    variable being declared.
  • Structure definitions include a tag, member
    elements, and a variable definition.
  • The variable definition is optional.

7
Structures
Structures
  • Structure definitions inform the compiler what
    the structure will look like.
  • struct flightType
  • char flightNum7 / 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.

8
Structures
Structures
  • To allocate memory for a struct, we declare a
    variable using the new structure definition type.
  • struct flightType plane
  • Structure members are laid
  • out in the order specified
  • by the definition.
  • Memory is now allocated,
  • and can be accessed as
  • individual members of thisvariable with the
    dot
  • operator
  • plane.altitude 10000
  • plane.heading 800


plane.flightNum0 0x0000(SP)
plane.flightNum1 0x0002(SP)
plane.flightNum2 0x0004(SP)
plane.flightNum3 0x0006(SP)
plane.flightNum4 0x0008(SP)
plane.flightNum5 0x000a(SP)
plane.flightNum6 0x000c(SP)
plane.altitude 0x000e(SP)
plane.longitude 0x0010(SP)
plane.latitude 0x0012(SP)
plane.heading 0x0014(SP)
plane.airspeed 0x0016(SP)

9
Structure Example
Structures
include ltstdio.hgt include ltstring.hgt struct
person char name80 int ssn struct
person barney, fred int main() strcpy(barney.
name, "Rubble, Barney") barney.ssn
555234561 strcpy(fred.name, "Flintstone,
Fred") fred.ssn 123451234 printf(\ns
d", fred.name, fred.ssn) printf(\ns d",
barney.name, barney.ssn)
10
Typedefs
typedefs
  • Using Naturally Named Data Types

11
Why typedef?
typedefs
  • You use variables with logical names.
  • Why not use data types with logical names?
  • Is an int 8-bits, 16-bits, 32-bits?
  • Whats a long?
  • Better question why memorize it?
  • Most integer data types are platform dependent!!!
  • typedefs make your code more portable.
  • Syntax
  • typedef lttypegt ltnamegt

12
How To Use typedefs
typedefs
  • Create a logical data type scheme.
  • A signed 8-bit number could be "s8"
  • An unsigned 16-bit number could be "u16"
  • Create a typedef.h file for each
    microcontroller platform you use.
  • include "typedef.h" in each of your files.
  • Use your new data type names.
  • typedef unsigned int u16
  • typedef unsigned char u8
  • u16 number

13
typedef.h Example
typedefs
  • typedef unsigned char u8
  • typedef signed char s8
  • typedef unsigned short u16
  • typedef signed short s16
  • typedef unsigned long u32
  • typedef signed long s32
  • Replace
  • unsigned char variable
  • with
  • u8 variable

14
typedefs
typedefs
  • Typedef declarations provide no additional
    functionality.
  • Makes code more readable by giving
    application-specific names to variable types.
  • typedef int Color
  • typedef struct flightType Flight
  • Color pixels500
  • Flight plane1, plane2

15
Structures in Structures
structs in structs
  • One field of a struct can be another structure

struct addressStruct char street80 char
city32 int zipCode struct person char
initials4 int ssn int height int
weight struct addressStruct address
tom int main() tom.ssn 555123456 tom.weigh
t 150 tom.address.zipCode 84062
person
initials
ssn
height
weight
address
street
city
zipCode
16
Arrays of Structures
Array of structs
  • Can declare an array of structs
  • typedef struct flightType
  • char flightNum7 / 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 planes100
  • Each array element is a structure.
  • To access a member of a particular element in the
    array you can use the . dot operator
  • planes34.altitude 10000

17
Pointers and Structures
struct Pointers
  • Pointers can point at structures

struct person char name80 int ssn
barney, rubble int main() rubble
barney strcpy((rubble).name, Rubble,
Barney) (rubble).ssn 555234561 printf(s
d\n, (rubble).name, (rubble).ssn)
strcpy(rubble-gtname, Rubble, Barney)
rubble-gtssn 555234561 printf(s d\n,
rubble-gtname, rubble-gtssn)
18
Pointers and Structures
struct Pointers
  • Since pointers can point to structures, then its
    easy to make links between structures.

tom
struct person char initials2 int 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-gtheight)
19
Memory Usage Heaps
Dynamic Memory Allocation
0x0000
  • Variable memory is allocated in three areas
  • Global data section
  • Run-time stack
  • Dynamically allocated - heap
  • Global variables are allocated in the global data
    section and are accessible after declaration.
  • Local variables are allocated during execution on
    the stack.
  • Dynamically allocated variables are items created
    during run-time and are allocated on the heap.
  • malloc() allocates memory
  • free() frees memory

SFRs
0xffff
20
Dynamic Memory Allocation
Dynamic Memory Allocation
  • The sizeof() function determines how much space
    is necessary for allocation.

include ltstdio.hgt include ltstdlib.hgt int
main() int dynArray double ddynArray /
Allocate space for 16 ints / dynArray (int
)malloc( 16 sizeof(int) ) dynArray6
65 dynArray12 2 / Allocate space for 20
doubles / ddynArray (double )malloc( 20
sizeof(double) )
21
Dynamic Memory Allocation
Dynamic Memory Allocation
  • Dynamic memory allocation using malloc() is used
    for many kinds of programs.
  • When data size is unknown or variable.
  • When building abstract structures like trees and
    linked lists.
  • 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.

22
Dynamic Memory Allocation
Dynamic Memory Allocation
  • Once allocated, the memory belongs to your
    program until it terminates or is free()d.

include ltstdio.hgt include ltstdlib.hgt main()
int dynArray / Allocate space for 16 ints
/ dynArray (int )malloc( 16 sizeof(int)
) dynArray6 65 dynArray12
2 doSomething( dynArray ) free( dynArray )
23
Pointers, Structures, malloc()
Dynamic Memory Allocation
  • Common to let malloc() create space for structures

struct person char initials2 int 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-gtinitials, "tj, 2) tom-gtssn
555235512 tom-gtfather bill tom-gtmother
susan susan-gtheight 68 / Since tom is now
a pointer, tom-gtmother-gtheight is correct.
/ printf(\nTom's mother's height is d",
tom-gtmother-gtheight)
24
union
union
  • A union is a value that may have any of several
    representations or formats or a data structure
    that consists of a variable which may hold such a
    value.
  • 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.

25
union Example
union
include ltstdio.hgt union char c int i
x int main() int i char c x.c x.i
0x12345678 printf("\ni 08x\n", x.i) for
(i0 ilt4 i) printf(" 02x", ci)
26
union Example
union
union char c int i float f double d
x x.c 'z' x.i 5180 x.f 3.14 x.d
3.141592653589793
char c x.c int i x.i float f
x.f double d x.d printf("\nc p",
c) printf("\ni p", i) printf("\nf p",
f) printf("\nd p", d)
27
Bit Fields
Bit Fields
  • Allow specification of some very small objects of
    a given number of bits in length.
  • Allow specification of fields within some
    externally produced data files.
  • Can only be declared inside a structure or a
    union.
  • No guarantee of the ordering of fields within
    machine words, so programs will be non-portable
    and compiler-dependent.
  • Be careful using them. It can require a
    surprising amount of run-time code to manipulate
    these things and you can end up using more space
    than they save.
  • Bit fields do not have addressesyou can't have
    pointers to them or arrays of them.

28
Bit Fields Example
Bit Fields
pragma pack(push,1) // BYTE align in memory (no
padding) typedef struct // (total 16 bits--a
unsigned short) unsigned short sec 5 //
low-order 5 bits are the seconds unsigned short
min 6 // next 6 bits are the minutes unsigned
short hour 5 // high-order 5 bits are the
hour FATTime pragma pack(pop) // End of
strict alignment pragma pack(push,1) // BYTE
align in memory (no padding) typedef struct //
(total 16 bits--a unsigned short) unsigned
short day 5 // low-order 5 bits are the day
unsigned short month 4 // next 4 bits are the
month unsigned short year 7 // high-order 7
bits are the year FATDate pragma pack(pop) //
End of strict alignment
29
Bit Fields Example
Bit Fields
typedef struct FATTime time FATDate
date DirEntry void setTimeDate(DirEntry
dir) time_t a struct tm b
time(a) b localtime(a) dir-gtdate.year
b-gttm_year 1900 - 1980 dir-gtdate.month
b-gttm_mon dir-gtdate.day b-gttm_wday
dir-gttime.hour b-gttm_hour dir-gttime.min
b-gttm_min dir-gttime.sec b-gttm_sec
return // end setDirTimeDate
30
Linked List Data Structure
Linked List
  • 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.

31
Simple Linked List Example
Linked List
typedef struct element int value struct
element next Element Element
list Element newElement(int v) Element
tmp tmp (Element)malloc( sizeof(Element)
) tmp-gtvalue v tmp-gtnext NULL return
tmp int main() / Create linked list
/ list newElement(50) list-gtnext
newElement(75) list-gtnext-gtnext
newElement(99)
32
Linked Lists vs Arrays
Linked List
  • Advantages of a linked list -
  • Dynamic size.
  • Easy to add additional nodes.
  • Easy to add or remove nodes from the middle of
    the list by adding or redirecting links.
  • Advantages of an array -
  • Can easily and quickly access arbitrary elements.
  • In a linked list in order to access the 5th
    element of the list you must start at the head
    and follow the links through four other nodes.

33
Linked List Creation
Linked List
  • There are three steps required to create a linked
    list -
  • Allocate space for predefined structure.
  • Fill in the structure fields.
  • Link the structure into the list using pointers.

struct element newElement(int v) struct
element tmp tmp (struct element)malloc(
sizeof(struct element) ) tmp-gtvalue v
tmp-gtnext NULL return tmp
34
Pre-pending Items to a Linked List
Linked List
/ Prepend an item to start of oldList, returning
ptr to new list / struct element prepend(struct
element item, struct element oldList) item-gtn
ext oldList return item int
main() struct element tmp list
newElement(45) / Prepend item to list / tmp
newElement(30) list prepend(tmp,
list) / Can prepend in one statement / list
prepend(newElement(10), list) printList(list)

35
Appending Items to a Linked List
Linked List
/ Append an item to the end of oldList,
returning ptr to list / struct element
append(struct element item, struct element
oldList) struct element tmp if (oldList
NULL) return item / oldList is empty / tmp
oldList while (tmp-gtnext ! NULL) tmp
tmp-gtnext / Search for end of list
/ tmp-gtnext item return oldList int
main() / Append some items to end of list
/ list append(newElement(200), list) list
append(newElement(201), list) list
append(newElement(202), list) printList(list)
36
Inserting Items into a Linked List
Linked List
  • Search to find the proper location
  • link the new record into its proper place.
  • multiple cases to consider
  • list is empty
  • item belongs at front of existing list
  • item belongs somewhere in middle of existing list
  • item belongs at end of existing list

37
Inserting Items into a Linked List
Linked List
struct element insert(struct element item,
struct element oldList) struct element
tmp / oldList is empty / if (oldList
NULL) return item / The new item goes first
(pre-pend) / if (item-gtvalue lt
oldList-gtvalue) item-gtnext oldList return
item / Search for proper location / tmp
oldList while ((tmp-gtnext ! NULL)
(tmp-gtnext-gtvalue lt item-gtvalue)) tmp
tmp-gtnext item-gtnext tmp-gtnext tmp-gtnext
item return oldList
38
Inserting Items into a Linked List
Linked List
struct element insert(struct element item,
struct element oldList) int main() / Insert
some items into list / list
insert(newElement(65), list) list
insert(newElement(2), list) list
insert(newElement(97), list) list
insert(newElement(3), list) list
insert(newElement(300), list) printList(list)

39
Freeing Items in a Linked List
Linked List
  • 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 youre standing on.

int main() / Create a linked list / list
newElement(50) list-gtnext newElement(75) lis
t-gtnext-gtnext newElement(99) free(list-gtnext-
gtnext) free(list-gtnext) free(list)
40
Printing Items in a Linked List
Linked List
  • Use a temporary pointer to walk down the list
  • print values as you go
  • end up with a newline

void printList(struct element ptr) if (ptr
NULL) printf("\n") else printf(" d",
ptr-gtvalue) printList(ptr-gtnext)
void printList(struct element ptr) struct
element tmp tmp ptr while (tmp !
NULL) printf( d, tmp-gtvalue) tmp
tmp-gtnext printf("\n")
41
Example 2
Example 2
  • Thermostat temperature entry

typedef unsigned int u16 typedef unsigned char
u8 enum SUN, MON, TUE, WED, THUR, FRI, SAT
typedef struct Setting_struct struct
Setting_struct link union u16 time
// dayhour/minute struct u8
day3 // day of week (0-6) u8
hour5 // hour (0-23) u8 minute //
minute (0-59) times date u8
high u8 low Setting
link
date
high
low
NULL NULL



42
Create New Node
Example 2
// create a new entry Setting newSetting(u8 day,
u8 hour, u8 minute, u8 high, u8 low) //
malloc a new node Setting temp
(Setting)malloc(sizeof(Setting)) // store
entries temp-gtdate.times.day day
temp-gtdate.times.hour hour
temp-gtdate.times.minute minute temp-gthigh
high temp-gtlow low // null link
temp-gtlink NULL return temp // end
newSetting
43
main
Example 2
enum SUN0, MON, TUE, WED, THUR, FRI, SAT
int main() Setting list NULL //
Create linked list list newSetting(MON, 6,
30, 22ltlt1, 20ltlt1) list-gtlink
newSetting(WED, 20, 30, 17ltlt1, 15ltlt1)
list-gtlink-gtlink newSetting(FRI, 8, 30, 22ltlt1,
20ltlt1) list-gtlink-gtlink-gtlink
newSetting(SAT, 18, 30, 20ltlt1, 18ltlt1)
026e
0256
0000
0266
025e
1e45
1e96
1ea3
1e31
2c
28
22
2c
28
24
1e
28
44
Insert Setting
Example 2
Setting insertSetting(Setting setting, Setting
oldList) Setting temp if (oldList
NULL) return setting // oldList is empty
// The new item goes first (pre-pend) if
(setting-gtdate.time lt oldList-gtdate.time)
setting-gtlink oldList return setting
// Search for proper location temp
oldList while (temp-gtlink ! NULL) if
(temp-gtdate.time setting-gtdate.time)
// replace temp-gthigh setting-gthigh
temp-gtlow setting-gtlow
free(setting) return oldList
if (temp-gtlink-gtdate.time gt
setting-gtdate.time) break temp temp-gtlink
// next setting-gtlink
temp-gtlink // insert temp-gtlink
setting return oldList // end
insertSetting
45
Print Setting
Example 2
char days "Sun", "Mon", "Tue",
"Wed", "Thu", "Fri", "Sat" void
printList(Setting ptr) Setting temp
temp ptr while (temp ! NULL)
printf("\ns 02d02d 4.1f-4.1f",
daystemp-gtdate.times.day,
temp-gtdate.times.hour,
temp-gtdate.times.minute,
(float)temp-gthigh /
2.0, (float)temp-gtlow
/ 2.0 ) temp temp-gtlink
printf("\n") // end printList
46
Final Test
Example 2
void main(void) Setting list NULL
eZ430X_init(CALDCO_1MHZ) // init board
lcd_init() // init LCD lcd_backlight(ON)
// Create linked list list
newSetting(MON, 6, 30, 22ltlt1, 20ltlt1)
list-gtlink newSetting(WED, 20, 30, 17ltlt1,
15ltlt1) list-gtlink-gtlink newSetting(FRI, 8,
30, 22ltlt1, 20ltlt1) list-gtlink-gtlink-gtlink
newSetting(SAT, 18, 30, 20ltlt1, 18ltlt1) //
Insert some items into list list
insertSetting(newSetting(MON, 6, 30, 24ltlt1,
18ltlt1), list) list insertSetting(newSetting(
SUN, 6, 30, 22ltlt1, 20ltlt1), list) list
insertSetting(newSetting(TUE, 6, 30, 22ltlt1,
20ltlt1), list) list insertSetting(newSetting(
MON, 6, 30, 20ltlt1, 10ltlt1), list) list
insertSetting(newSetting(SAT, 20, 30, 22ltlt1,
20ltlt1), list) printList(list) return
47
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com