SLIDE 1
Fri., 23 Oct. 2015 Please fill in the survey! (emailed to you on - - PowerPoint PPT Presentation
Fri., 23 Oct. 2015 Please fill in the survey! (emailed to you on - - PowerPoint PPT Presentation
Fri., 23 Oct. 2015 Please fill in the survey! (emailed to you on Monday) Reminder: Gator Day presentations at 11, lunch at noon (lunch is via sign-up--see me) Today: pointers and recursive data types For Monday: begin chapter 8 (Functions)
SLIDE 2
SLIDE 3
Models of Variables (Chapter 6)
reference model: a variable is a reference to a value. In this model, all variables behave like l-values; there is no notion of a “container” for a value, there’s just a value and the variable that refers to it. NOTE: of course there are “containers” (we also call this “memory”)! But in reference-model languages we don’t think about the containers.
SLIDE 4
Pointers
In a reference model language, every variable is a “pointer” to a value. In a value model language, the nearest we come to this is when a variable is used as an l- value (e.g., left side of an assignment). But some languages allow a special “pointer” data type.
SLIDE 5
Pointers
In a reference model language, every variable is a “pointer” to a value. In a value model language, the nearest we come to this is when a variable is used as an l- value (e.g., left side of an assignment). But some languages allow a special “pointer” data type.
SLIDE 6
Pointers in C
int a = 20, b = 30; int *c; /* pointer variable */ c = &a; /* “&” = “address of” */ *c = 40; /* “*” = “dereference” */ c = &b; *c = 50; printf(“a=%d,b=%d\n”,a,b); /* a=40,b=50 */
SLIDE 7
Nifty Pointer Tricks
We can use pointers to “mark” certain locations in memory, such as the midpoint of an array (see programs “ptrtricks2.c” and “ptrtricks2.c” in
- ct23 folder).
SLIDE 8
Data Types with Pointers
Examples: binary trees, linked lists, graphs (all topics from CMPSC 112). These usually include a pointer or reference variable. Java linked list:
public class Node { String value; Node next; ...
SLIDE 9
Do-It-Yourself Allocation
Java’s “new” command allocates the right amount of memory from heap memory, but in C we have to do it
- urselves with “malloc”:
struct node { char value[81]; struct node *next; }; struct node *n = (struct node *) malloc(sizeof(struct node));
SLIDE 10
Garbage Collection
When memory is no longer needed, it is collected, either automatically (e.g., Java), or manually by the user (e.g., C). In C, use the “free” function. (See “oops.c”) We discussed this in chapter 3--see slides from 11 Sept. and 14 Sept.
SLIDE 11