02 Pointers
02 Pointers
Other References
Pointers and Memory, by Parlante
Data Structures 2
What is a pointer?
A pointer is a reference to another item
the other item is sometimes called the "pointee"
the pointee is often a variable
the pointee can also be a function (a procedure)
Data Structures 3
Some declarations
Data Structures 4
Reference and dereference
Data Structures 5
Pointers and Pointees
numP = #
sumP = ∑
symP = &mySym;
*numP = 42;
*sumP = 17.0;
(*symP).val = 2;
Data Structures 6
Example from Pointers & Memory
Data Structures 7
What form does data take?
Integers
-1, 0, 255, 65535, ...
Floating point
1.5, 3.14159, 1E75, …
character strings
"abc", "def"
Data Structures 8
But real data is more complex
Airplane definition
engine count, crew count, passenger capacity, range, operating
cost per seat mile, …
Student record
name, student id, major, school address, home address, credits to
date, current enrollment, …
Major fields of study
responsible department, curriculum, students, ...
Data Structures 9
Why have structs?
twoSym.name = "two";
twoSym.val = oneSym.val+1;
Data Structures 10
What is a struct variable?
Data Structures 11
What can you do with a struct?
mySym = twoSym;
Data Structures 12
How can structs be costly?
Copying a struct is a nice automatic feature
but it can lead to a lot of copying
Data Structures 13
Pointers to the rescue
Take the address of a struct variable and store it in a
pointer variable
Then you can manipulate the pointers, leaving the original
data where it is and just moving pointer values around
An array of pointer values is one way to define a list of
objects (struct variables)
Data Structures 14
A short array of Symbol pointers
Symbol * char *
unsigned long
Symbol *
char
char *
unsigned long
char
Data Structures 15
Pointers allow you to link objects
oneSym char *
struct Node { unsigned long
struct Node *next; twoSym char *
struct Symbol *element;
}; unsigned long
threeSym char *
struct Node *nodeA;
struct Node *nodeB; unsigned long
struct Node *nodeC;
Data Structures 16
nodeA = malloc(sizeof(struct Node));
FatalErrorMemory(nodeA);
(*nodeA).next = nodeB;
(*nodeA).element = &oneSym; Three Linked Nodes
nodeB->next = nodeC;
nodeB->element = &twoSym;
0x80498f0 (one) points to 0x8049900
0x8049900 (two) points to 0x8049910
nodeC->next = NULL;
0x8049910 (three) points to (nil)
nodeC->element = &threeSym;
nodeP = nodeA;
while (nodeP != NULL) {
printf("%p (%s) points to %p\n",
nodeP,nodeP->element->name,nodeP->next);
nodeP = nodeP->next;
}
Data Structures