Lecture 12: Pointers

Feb 26, 2024  β”‚  Last updated Feb 27, 2024 by Charlotte Curtis

HTML Slides html β”‚ PDF Slides PDF

Where we left off

  • Reading and writing files
  • Stream behaviour
  • Command line arguments

Textbook Chapter 6, plus off-book

#include <fstream>

int main(int argc, char *argv[]) {
    ofstream output(argv[1]);
    output << "Writing to a file!\n";
    output.close();
    return 0;
}

Today’s topics

Textbook Chapter 9, kinda

Midterm Info

That mysterious issue from last lecture

And now, pointers!

“It’s easier to give someone your address than to make a copy of your house” – Something I read somewhere, probably Stack Overflow

Memory and Addresses

bg right:40% 120%

Allocating Memory: Example

bg right:40% 120%

int main() {
    int i = 42;
    int j;
    char c = 'K';
    double d = 3.14159;
    // ...
    return 0;
}

The memory addresses are integers, though usually hexadecimal (base 16)

The pointer type

bg right:40% 80%

Declaring pointers

The * is not part of the type!

While C++ allows the * to be placed anywhere between the type and the variable, you have to be very careful:

char *cptr; // pointer to a char
char* cptr2; // also a pointer to a char

int *ptr1, *ptr2; // Two pointers to ints
int* ptr3, ptr4; // ptr3 is a pointer to an int, ptr4 is an int

What happens when we declare a pointer?

When a program runs, it is given its own isolated memory space. While you might get segmentation faults by accessing invalid memory locations, you won’t bork your system or break another program.

Side tangent: Segmentation fault

Initializing pointers

In C++ 11, NULL was replaced with nullptr to avoid some ambiguity

The & operator

bg right:40% 120%

Assigning addresses to pointers

Consider the following:

int i = 42;
int *iptr = &i;
iptr = &j;

What just happened??

Let’s draw a diagram!

Now add on:

int *iptr2;
iptr2 = iptr;

Dereferencing pointers

Some Pointer Gotchas

Syntax Soup: exercise

Given the following, fill in the table to the right:

int x = 24;
int *iptr = &x;
char c;
char *cptr = &c;
ExpressionTypeExpressionType
xc
iptrcptr
&x&c
*iptr*cptr

Take a few minutes to try to answer this (in groups or independently), then we’ll go through the solution together

Coming up next



Previous: Lecture 11: File I/O and Command Line Arguments
Next: Lecture 13: Pointers continued