Lecture 5/8: Memory and Pointers


May 8, 2020

πŸ“‚Associated files

Pointers

CS 106B: Programming Abstractions

Spring 2020, Stanford University Computer Science Department

Lecturers: Chris Gregg and Julie Zelenski

An image of a pointer breed of dog


Slide 2

Announcements


Slide 3

Today's Goals:


Slide 4

Introduction to Pointers


Slide 5

Your computer's memory system

values (ints): 7 2 8 3 14 99 -6 3 45 11
index:  0   1   2   3   4   5   6   7   8   9 
values (strings): cat dog apple tree shoe hand chair light cup toe
address:  10   11   12   13   14   15   16   17   18   19 
string pet = "cat";
pet:
cat
10

Slide 6

A pointer is just a memory address

string pet = "cat";
pet:
cat
10
petPointer:
10
1234

Slide 7

Introduction to Pointers

What is a pointer??

a memory address!

Slide 8

Introduction to Pointers

petPointer:
10
1234
β†’
pet:
cat
10
petPointer:
 
β†’
pet:
cat

Slide 9

What you need to know about pointers


Slide 10

Pointer Syntax


Slide 11

Pointer Syntax

petPtr:
?
1234
β†’
?
petPtr:
?
1234
β†’
?
    
pet:
cat
10
petPtr:
10
1234
β†’
pet:
cat
10

Slide 12

Pointer Syntax

petPtr:
10
1234
β†’
pet:
cat
10

Slide 13

Pointer tips

petPtr:
?
1234
β†’
?
petPtr:
0
1234
β†’
nullptr (not a valid address)

Slide 14

Pointer tips


Slide 15

Pointer practice

nPtr:
0
7224
β†’
nullptr

Slide 16

Pointer Practice

nPtr:
0
7224
β†’
nullptr
n:
16
5432
nPtr:
5432
7224
β†’
n:
16
5432

Slide 17

Introduction to Pointers

What is a pointer??

a memory address!

Slide 18

Pointer Practice

sPtr:
0
6420
β†’
nullptr
s:
hello
9988
sPtr:
9988
6420
β†’
s:
hello
9988

Slide 19

Pointer practice

sPtr:
0
6420
β†’
nullptr
s:
hello
9988

Slide 20

Pointer Practice

sPtr:
9988
6420
β†’
s:
hello
9988
sPtr:
9988
6420
β†’
s:
goodbye
9988

Slide 21

Pointer Practice

sPtr1:
0
6420
β†’
nullptr
sPtr2:
0
2232
β†’
nullptr
s:
hello
9988
sPtr1:
9988
6420
β†’
s:
hello
9988
sPtr2:
0
2232
β†’
nullptr
sPtr1:
9988
6420
β†’
s:
hello
9988
sPtr2:
9988
2232
β†—οΈŽ
sPtr1:
9988
6420
β†’
s:
goodbye
9988
sPtr2:
9988
2232
β†—οΈŽ

Slide 22

Introduction to Pointers

What is a pointer??

a memory address!

Slide 23

More information about addresses

sPtr1:
0xfcab0
0xfe01a
β†’
s:
goodbye
0xfcab0
sPtr2:
0xfcab0
0xfe5c2
β†—οΈŽ

Slide 24

Binky


Slide 25

If we have time: Copy Constructors

An image of a rectangle encasing the qt logo

r.width:
0x99
0x61
β†’
3
0x99
r.height:
0x9f
0x63
β†’
4
0x9f
r.width:
0x99
0x61
β†’
3
0x99
←
r2.width:
0x99
0x65
r.height:
0x9f
0x63
β†’
4
0x9f
←
r2.height:
0x9f
0x67