Discussion - PowerPoint PPT Presentation

1 / 36
About This Presentation
Title:

Discussion

Description:

height. weight. address. street. city. zipCode. person. ECEn/CS 124. Discussion #18 ... mother is a pointer to a struct and thus mother- height is correct. ... – PowerPoint PPT presentation

Number of Views:60
Avg rating:3.0/5.0
Slides: 37
Provided by: paulr7
Category:

less

Transcript and Presenter's Notes

Title: Discussion


1
Schedule
2
Chapter 19 - Pointers and Structures
3
Celestial Structure
  • DC 88119
  •   119 Organize yourselves prepare every needful
    thing and establish a house, even a house of
    prayer, a house of fasting, a house of faith, a
    house of learning, a house of glory, a house of
    order, a house of God

4
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
  • a variable definition (optional)

5
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 /
  • The structure definition does not allocate memory.

6
Structures

plane.flightNum0 plane.flightNum1 plane.flight
Num2 plane.flightNum3 plane.flightNum4 plane
.flightNum5 plane.flightNum6 plane.altitude p
lane.longitude plane.latitude plane.heading pla
ne.airspeed
  • To allocate memory for a struct, we need to
    declare a variable using the new structure
    definition type
  • struct flightType plane
  • struct members are laid out in the order
    specified by the definition.
  • Memory is now allocated, and we can access
    individual members of thisvariable with the
    dot operator
  • plane.altitude 10000
  • plane.heading 800

10000
800
7
Structure Example
include include struct
person char name80 long int ssn struct
person barney, fred int main()
strcpy(barney.name, "Rubble,
Barney") barney.ssn 555234561 strcpy(fred.na
me, "Flintstone, Fred") fred.ssn
123451234 printf(\ns d", fred.name,
fred.ssn) printf(\ns d", barney.name,
barney.ssn)
Does not allocate memory
Allocates two memory structs
8
Structures in Structures
  • One field of a struct can be another structure

struct addressStruct char street80 char
city32 int zipCode struct person char
initials4 long int ssn int height int
weight struct addressStruct address tom int
main() tom.ssn 555123456 tom.weight
150 tom.address.zipCode 84062
9
typedefs
  • Define a new data type by giving a name to a
    predefined type.
  • Syntax
  • typedef
  • Examples
  • typedef int Color
  • typedef struct flightType Flight
  • typedef struct ab_type int a
    double b ABGroup

Equivalent struct ab_type ABGroup
10
typedefs
  • typedef declarations provide no additional
    functionality.
  • Makes code more readable by giving
    application-specific names to variable types.
  • Color pixels500
  • Flight plane1, plane2
  • struct ab_type testa
  • ABGroup testb

Equivalent struct ab_type ABGroup
11
typedef
include include typedef
struct person char name80 long int ssn
Person Person barney, fred int main()
strcpy(barney.name, "Rubble,
Barney") barney.ssn 555234561 strcpy(fred.na
me, "Flintstone, Fred") fred.ssn
123451234 printf(\ns d", fred.name,
fred.ssn) printf(\ns d", barney.name,
barney.ssn)
12
Structures in Structures
  • One field of a typedef can be another typedef

typedef struct addressStruct char
street80 char city32 int zipCode
Address typedef struct person char
initials4 long int ssn int height int
weight Address address Person Person
tom int main() tom.ssn 555123456 tom.weig
ht 150 tom.address.zipCode 84062
person
initials
ssn
height
weight
address
street
city
zipCode
13
Arrays of Structures
  • Can declare an array of structs
  • Flight planes100
  • Each array element is a struct.
  • To access a member of a particular element in the
    array you can use the . dot operator
  • planes34.altitude 10000

14
Pointers and Structures
  • Pointers can point at structs

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

tom
struct person char initials4 long 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-height)
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
16
Pointers and Structures
  • Since pointers can point to structs, then its
    easy to make links between structs.

tom
typedef struct person char initials4 long
int ssn int height struct person
father struct person mother Person /
Declare variables and initialize them at the same
time / Person tom "tj", 555235512, 74, NULL,
NULL Person bill "wj", 351003232, 75,
NULL, NULL 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 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
17
malloc()
  • void malloc(int size) Memory allocate
  • Give me a chunk of memory
  • Allocate size bytes of memory
  • NOT from the stack but from the heap
  • A pointer to the memory is returned as a void
    pointer
  • void pointer must be cast to be a pointer to the
    desired data type

int dynArray (int )malloc( 16 sizeof(int) )
Allocate 16 ints (32 bytes on a standard
processor)
Cast as an int
18
Memory Usage Heap
0x0000
Trap Vector Table
Interrupt Vector Table
  • 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 from all parts of the
    program.
  • Local variables are allocated during execution on
    the run-time stack.
  • Dynamically allocated variables are items created
    during run-time and are allocated on the heap.
  • malloc() allocates memory

Trap Routines
Operating System
0x3000
Program Code
PC
R4
Global Data Section(Global and Static vars)
Heap(Dynamically allocated vars)
R6
Run-Time Stack(Local and Auto vars)
R5
I/O Space
0xFFFF
19
Dynamic Memory Allocation
  • The sizeof() function determines how much space
    is necessary for allocation.

include include int
main() int dynArray double ddynArray int
dsize 20 / Allocate space for 16 ints
/ dynArray (int )malloc( 16 sizeof(int)
) dynArray6 65 dynArray12 2 /
Allocate space for 20 doubles / ddynArray
(double )malloc( dsize sizeof(double) )
20
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 structs 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.

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

include include main()
int dynArray / Allocate space for 16
ints / dynArray (int )malloc( 16
sizeof(int) ) dynArray6 65 dynArray12
2 doSomething( dynArray ) free( dynArray )
22
Pointers, Structures, malloc()
  • Common to let malloc() create space for structures

struct person char initials4 long 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-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)
23
The Linked List Data Structure
  • A linked list is an ordered collection of
    nodes,each of which contains some
    data,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.

Node 0
Node 1
Node 2
NULL
24
Simple Linked List Example
typedef struct element int value struct
element next Element Element
list Element newElement(int v) Element
tmp tmp (Element)malloc( sizeof(Element)
) tmp-value v tmp-next NULL return
tmp int main() / Create linked list
/ list newElement(50) list-next
newElement(75) list-next-next
newElement(99)
25
Simple Linked List Example
struct element int value struct element
next list struct element newElement(int v)
struct element tmp tmp (struct
element)malloc( sizeof(struct element)
) tmp-value v tmp-next NULL return
tmp int main() / Create linked list
/ list newElement(50) list-next
newElement(75) list-next-next
newElement(99)
26
Linked Lists vs Arrays
  • 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.

27
Linked List Creation
  • 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.

Element newElement(int v) Element tmp
tmp (Element)malloc( sizeof(Element) )
tmp-value v tmp-next NULL return
tmp
28
Prepending Items to a Linked List
/ Prepend an item to start of oldList, returning
ptr to new list / Element prepend(Element
item, Element oldList) item-next
oldList return item int main() 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)
29
Appending Items to a Linked List
/ Append an item to the end of oldList,
returning ptr to list / Element append(Element
item, Element oldList) Element tmp if
(oldList NULL) return item / oldList is
empty / tmp oldList while (tmp-next !
NULL) tmp tmp-next / Search for end of
list / tmp-next 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)
30
Adding a Node
  • Create a new node with the proper info.Find the
    node (if any) with a greater vehicleID.Splice
    the new node into the list

new node
Node 0
Node 1
Node 2
NULL
31
Inserting Items into a 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 (prepend)
  • item belongs somewhere in middle of existing list
  • item belongs at end of existing list (append)

32
Inserting Items into a 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
(prepend) / if (item-value value)
item-next oldList return
item / Search for proper location / tmp
oldList while ((tmp-next ! NULL)
(tmp-next-value value)) tmp
tmp-next item-next tmp-next tmp-next
item return oldList
33
Inserting Items into a Linked List
struct element insert(struct element item,
struct element oldList) int main() / Insert
some items into list / struct element list
NULL 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)

34
Deleting a Node
  • Find the node that points to the desired
    node.Redirect that nodes pointer to the next
    node (or NULL).Free the deleted nodes memory.

Node 0
Node 1
Node 2
NULL
35
Freeing Items in a 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 you must be
    careful not to saw off the limb youre standing
    on.

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

void printList(Element ptr) Element
tmp tmp ptr while (tmp ! NULL)
printf( d, tmp-value) tmp
tmp-next printf("\n")
void printList(Element ptr) if (ptr NULL)
printf("\n") else printf(" d",
ptr-value) printList(ptr-next)
Write a Comment
User Comments (0)
About PowerShow.com