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)
Models of Variables (Chapter 6) Two “models” of variables (pp. 225): value model: a variable is a named container filled with a value; this value can change. In this model, variables can be l-values (the container) or r-values (the container’s value): int a = 10,b; Java, C, C++, l-value r-value etc. b = a;
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.
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.
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.
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 */
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 oct23 folder).
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; ...
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 ourselves with “ malloc ”: struct node { char value[81]; struct node *next; }; struct node *n = (struct node *) malloc(sizeof(struct node));
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.
Dangling References When a pointer no longer points to anything, it is a “dangling reference”. See “oops.c”.
Recommend
More recommend