Lecture 13: Pointers continued

Feb 28, 2024  β”‚  Last updated Feb 29, 2024 by Charlotte Curtis

HTML Slides html β”‚ PDF Slides PDF

Where we left off

  • Intro to pointers
  • Assigning and dereferencing pointers

Textbook Chapter 9ish

int x = 5;
int *ptr = &x;

*ptr = 10;
cout << "x: " << x << endl;

Today’s topics

… you get the point

Textbook Chapter 9ish, still

Pointers and const

Things are getting rather const-y

The same info in table form

DeclarationCan change valueCan change pointer
int *ptrYesYes
const int *ptrNoYes
int * const ptrYesNo
const int *const ptrNoNo

All this gets rather confusing

Pointers and Arrays

Pointers and Arrays

char A[10] = "Hello";
char *cptr = A; // no &, because A is already an address

Pointers can be used to iterate through arrays!

Side tangent: Pointer arithmetic

Pointers and Structures

Pointers and Structures

emoji Pointer check-in 1/2

Which of the following operators can not be used with pointers?

  1. &
  2. *
  3. ++
  4. []
  5. /

emoji Pointer check-in 2/2

Which statements are true about the following code snippet? Select all that apply.

  1. x is a pointer to an int
  2. p points to x
  3. p could be used to change the value of x
  4. p could be reassigned to point to y
  5. The const has no effect
int x = 0;
int y = -1;
const int *p = &x;
cout << "x is " << x
     << " and y is " << y << endl;

Pointers and functions

Passing pointers by value

Kinda confusing, let’s visualize

Passing by reference

Protecting what a pointer points to

What can be passed as a pointer?

Given the following function prototypes and variable declarations:

void foo(int *ptr);
void bar(int *&ptr);
int x = 0;
int *iptr = &x;

Which of the following are valid?

  1. foo(5);
  2. foo(&5);
  3. foo(&x);
  4. foo(iptr);
  5. foo(&iptr);
  1. bar(5);
  2. bar(&5);
  3. bar(&x);
  4. bar(iptr);
  5. bar(&iptr);

Side tangent: typedef

Returning a pointer

Dynamic allocation preview

The heap and the stack

h:200 flavour

h:200 flavour

The new operator

To create a variable on the heap, use the new operator:

int *ptr; // memory for pointer is on the stack
ptr = new int; // what it points at is on the heap

This does the following:

  1. Allocates enough memory on the heap for an int
  2. Returns the address of the allocated memory

Some things to be cautious of:

  • The allocated int can only be accessed through ptr!
  • After you’re done with it, you must delete it to free the memory

Coming up next

Textbook Section 9.2



Previous: Lecture 12: Pointers
Next: Lecture 14: Dynamic Allocation and Midterm Review