7.1.3 Pointers and Functions

As you saw in the previous lessons, the idea behind pointers is that they point to a location in the heap that holds a value. This means you need to track both the pointer value (representing a memory location) and the heap value associated with that pointer.

A traditional variable only has one value to keep track of, but now you need to be concerned with two different values. This is where errors and debugging can get confusing. In this example, you will look at how to handle both values and where to use them.

Functions That Take a Pointer

If a function takes a pointer type as a parameter, the only valid arguments will essentially be memory addresses. This means you either need to pass it another pointer value (not the dereferenced value), or the reference to a traditional variable using the & you saw earlier.

Take the following function header:

void add5(int *num);

If you have an integer pointer variable it will get passed directly:

int *num;
num = new int;
*num = 5;

add5(num);

Notice the type for num is a int pointer and the parameter takes an int pointer, so nothing else is needed.

Instead, if num is now a standard stack variable, you need to pass the reference to the variable using the &:

int num;
num = 5;

add5(&num);

In this case, the function will still update the value in the calling function without the need to return anything.

Functions That Take a Value

When a function takes an actual value as a parameter, you will need to either pass a value or pass the dereferenced pointer. Take this header:

void add5(int num);

Given a pointer, you can pass the value to it in this fashion:

int *num;
num = new int;
*num = 5;

add5(*num);

Notice that the value is sent by dereferencing the pointer.

Additional Examples

In the example below, you will notice a few other additional examples that do not need much explanation. Just like other variable types, pointers can be return values by adding the * after the return variable type and before the function name.

Additionally, you saw that functions can use pass-by-reference to pass a value to a function to be updated without a return value. In a similar way, you can pass the reference directly to a pointer parameter. Updates made to the pointer value in the function will then be reflected back in the calling function.

Last updated