1 of 13

CSci 13500

Topic 17: Pointers Part 1

2 of 13

Itinerary

  • Memory
  • Pointers

2

3 of 13

Memory

4 of 13

How memory works

All instructions made by your code is stored within the memory stack. The memory stack is all the memory that the compiler knows your program is going to use. This includes:

  • Variable declaration
  • Non-recursive function calls
  • Code logic and operations

For things that are created dynamically within your program, they are allocated within the memory heap.

4

5 of 13

Each address stores 1 byte of memory. Depending on the variable, it can take up multiple memory addresses.

5

6 of 13

The Heap

The heap is similar to the stack, except that it stores any dynamic memory. Dynamic memory is any memory that is not expected by the compiler but is expected during runtime.

Whenever you allocate memory dynamically, you reserve space in the heap and you have it there for the runtime of the program.

However, how do we access this dynamic memory?

6

7 of 13

Pointer

8 of 13

Pointers!

A pointer is a data type that stores addresses. Literally pointing at an address.

The pointer, when declared, tells you what type of data the address stores.

8

9 of 13

Assigning

For assigning a variable to be a pointer, you would add a * character.

If you want the address of a variable, you would use the & character to obtain the address. (Hmmm, have we seen this before?)

int * pointer = nullptr; // initialize an integer pointer to point at nothing

int value = 5; // normal variable declaration

pointer = &value; // pointer stores the address of value (NOT THE ACTUAL

CONTENT)

9

10 of 13

This isn’t dynamic!

Looking at the example, this seems redundant and doesn’t really explain the importance of a pointer. However, they are super important when tied with a new keyword.

10

11 of 13

new

The “new” keyword is used to dynamically allocate space within the heap. That is why you could never make a variable called new because it would conflict with this keyword.

int * pointer = nullptr; // initialize an integer pointer to point at nothing

pointer = new int; // new int returns a NEW address in the heap and we store

it in pointer

11

12 of 13

How do we modify the value stored in it?

There are a couple of ways. In these examples we would do the following:

*pointer = 5;

What this means is the following: We dereference the pointer (using *), and we set the value of the address of where that pointer is storing to 5.

That’s a lot.

12

13 of 13

Why is it important, again?

When working with more sophisticated software, you will be making your own classes (more on next week) that sometimes you want to dynamically create. You may not know how much memory you are going to need.

Therefore pointers are important to keep track of each thing that we dynamically allocate.

Now it comes down on how to manage it… and maybe some examples to go along with it.

13