Note

Goals

This part continues our hands-on practice with pointers.

  1. Use a pointer to a pointer to create or resize an array
  2. Distinguish arrays of pointers from rectangular arrays
  3. Compare copying an address with copying an allocated object
  4. Trace how a library function updates a caller’s pointer

Note

Prerequisites

  1. Completed Part 1
  2. Gone through Lecture 6: Dynamic Memory Allocation, including malloc, realloc, and free

Work through this part after Lecture 6.
The strtol() example later in this part is an additional application of pointers to pointers;
we explain what the function does before using it.

Click Edit to write your code, Run to see what happens, and Reset to start again.

Contents

Creating or Resizing an Array Through a Pointer

In Part 1, we changed a caller’s pointer to refer to a different integer.
Now we will change a caller’s pointer to refer to dynamically allocated memory.
There are certain POSIX library functions that need to take a pointer to a pointer. The best example we know happens to be getline.
Let’s see a very similar thing in action.

In the playground below, you should see an empty function
called void create_or_resize(int **arr_ptr). This function takes the address of a pointer to the first element of an array.

This means if we dereference arr_ptr, we will get a pointer. What is the value of this pointer?
The value of the pointer is the address of the first element of an integer array,
or NULL before allocation.

Important (Please Read This Slowly): create_or_resize as a function needs to take
the address of a pointer.
This means that create_or_resize should never be given NULL as input.
The pointer variable whose address we pass in is an object, so its address is not NULL.
Its stored value, on the other hand, can be NULL.

In void create_or_resize(int **arr_ptr), we want you to implement the following behaviour:

  1. If arr_ptr is an address of a pointer whose value is NULL,
    then we should set to point to an allocation of five integers, and fill it out with values

  2. On the other hand, if arr_ptr is an address of a pointer whose value is not
    NULL (and points to a live allocation from malloc, calloc, or realloc), please reallocate the array pointed at by *arr_ptr (notice we had to dereference the input once)
    to make it hold five integers. Then fill it out with values

Again, we say it again: arr_ptr is a pointer to a pointer.
arr_ptr is not the array itself. On the other hand, *arr_ptr gets us the address
of the first element of the array
, or NULL before allocation.

This means, to see if we were pointing at a pointer whose value is NULL,
you should check whether *arr_ptr == NULL.

After you write that, we want you to look at main, and notice that we can either now pass in the address
of a pointer that points to an existing heap-allocated array,
or even the address of a pointer that points to nothing. Either way, the function will set the pointer that we pass in.
Pay special attention to how we pass in &array_1 and &array_2.

Keep the result of malloc or realloc in a temporary pointer and check it before updating *arr_ptr.
If allocation fails, print an error and call exit(EXIT_FAILURE).
Once your function is ready, uncomment the output block in main() to check both arrays.

create-or-resize.c
#include <stdio.h>
#include <stdlib.h>
 
void create_or_resize(int **arr_ptr) {
    // Resize *arr_ptr to hold five integers, then fill it with 0 to 4
    // Check for allocation failure before changing *arr_ptr
    // Your code here
}
 
int main(void) {
    int *array_1 = malloc(3 * sizeof(int));
    int *array_2 = NULL;
    if (array_1 == NULL) {
        return 1;
    }
 
    create_or_resize(&array_1);
    create_or_resize(&array_2);
 
    // Once your function is implemented, uncomment this block to check it
    /*
    printf("Array 1 contents: ");
    for (size_t idx = 0; idx < 5; ++idx) {
        printf("%d, ", array_1[idx]);
    }
    printf("\nArray 2 contents: ");
    for (size_t idx = 0; idx < 5; ++idx) {
        printf("%d, ", array_2[idx]);
    }
    printf("\n");
    */
    free(array_1);
    free(array_2);
}
Ready

2D Arrays, and Beyond

Okay, so the previous section might have made you a little confused. “Isn’t it a 2D array”?

Well technically, something like a int ** is really just a pointer to a pointer. However you want
to treat that type, is up to you, the programmer. It also depends on context.

In the previous section, we saw examples where we wanted to take in the address of a pointer.
That was because we wanted to change the pointer itself.

The other common use-case is to access an array of pointers, each pointing to a row.
So how does this look like in memory?

An array of pointers to rows

You should think of this in two steps. In this representation, we use a variable of type int **ptr.
ptr’s value is actually:

  1. The address of the first element in some array
  2. That array is really an array of pointers. (i.e. an array of int *)

You can try looking at the diagram above, we hope that helps.

Generalising this pointer-based representation, you can imagine how another level might look… That’s right! int ***ptr;. Gosh.

This is different from a rectangular C array declared as int matrix[2][3].
That array contains two rows of three integers stored together, with no array of row pointers.
When it decays, its pointer type is int (*)[3], not int **.

Pointer Equality vs. Pointee Value Equality

We now need to talk about a super important concept: How to copy something. Look at the following snippet of code below,
and we want you to figure out how many copies of the allocated object are on the heap:

#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
    int *ptr1 = malloc(sizeof(int));
    if (ptr1 == NULL) {
        return 1;
    }
    *ptr1 = 0;
 
    int *ptr2 = ptr1;
    // so now ptr2 points to an integer, whose value is 0;
 
    printf("Same address: %d\n", ptr1 == ptr2);
    printf("Same value: %d\n", *ptr1 == *ptr2);
    free(ptr1);
}
Ready

How many copies of this heap-allocated integer are there?

Two pointers to one allocation

The way you should see it, is that we copied the address, but not the heap-allocation itself. So we have
two different pointers, but both of them hold the same address. So they point to the same thing.

What if we wanted to make two different copies? So let’s look at the following code.
On the lines that create ptr2 and assign *ptr2, we want you to take note of what’s going on here. We have to make a separate allocation,
then on the assignment line, we’re dereferencing both pointers to copy out their values.

#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
    int *ptr1 = malloc(sizeof(int));
    if (ptr1 == NULL) {
        return 1;
    }
    *ptr1 = 0;
 
    int *ptr2 = malloc(sizeof(int));
    if (ptr2 == NULL) {
        free(ptr1);
        return 1;
    }
    *ptr2 = *ptr1;
 
    printf("Same address: %d\n", ptr1 == ptr2);
    printf("Same value: %d\n", *ptr1 == *ptr2);
    free(ptr2);
    free(ptr1);
}
Ready

So this time around, we will see that when we dereference their pointers, the values are the same. But!
The pointer values themselves (i.e. the addresses) are different. So there really are two copies floating around.

Situations Where Pointers Arise

As a rough summary of Parts 1 and 2, so far:

  1. We’ve seen small examples on how to use pointers to change values inside functions
  2. We’ve seen how we can manipulate pointers (or arrays) from inside functions
  3. We’ve seen how the meaning of something like int ** might depend on what we want to use it for.
    We might either be taking in the address of a pointer, or we could be passing in an array of pointers. It really depends. Sometimes it’s even a mix of both

One of Our Favourite Examples

A great example of an existing function that has a mix of how it treats pointers is strtol().

Let’s think about what strtol() needs to do. It needs to, (1) take a string as input. And from that string, it needs to try
to read a number from the front of the string. It needs to (2) return the number it could read (if any). But it
also needs to (3) tell us where it stopped reading. It plans on doing so by setting a pointer we give it to
point to where it stopped trying to convert.

  1. To handle task (1), it takes as input a const char *. It treats this as a pointer to the first element of an array of characters
  2. To handle task (2), it’s just the return value of the function: long
  3. To handle task (3), because it now needs to set a pointer to point at where it stopped,
    it needs to take in the address of a pointer we have. So it also takes in a char **

Take note that for task 3, it is not a 2D array of characters but rather a pointer to a pointer.

This means to invoke strtol(), we might do it like so: strtol(str, &end, 10). Here str is a
pointer to the first character of a string we wish to convert. end is of type char *. So we’re passing in
the address of end (that’s why when we call the function, we’re using &end, notice the ampersand!).

So for example, when given a string str like "123abc", strtol() will get the address of the first character of the string.
Since it also separately took the address of another pointer that we gave it. Based on our example, it will set end to point at
the letter 'a' inside the string. Take a look at the diagram below to see what we mean.

strtol sets a pointer to the unconverted suffix

#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
    char *str = "123abc";
    char *end;
    long value = strtol(str, &end, 10);
    printf("Number: %ld\n", value);
    printf("Stopped at: %s\n", end);
}
Ready

Why Do Pointers Exist in C

Why would we ever want to use pointers? There are a few key reasons, some of which we don’t really stress
on right now (in CS1010), but it roughly revolves around a few key motivations.

  1. Efficiency
  2. Usability from the perspective of a function caller
  3. Dynamic memory allocation

(Efficiency) Let’s look this snippet of code:

void foo(char *str){
    str[0] = 't';
}
 
int main(void){
    char str[4] = "abc"; // here str is an array of 4 characters
    foo(str);
}

In C, it’s quite common for people to pass around arrays and strings. Again, we mentioned how array decay means that
in the snippet above, inside foo(), str is a pointer, not an array.

If instead it had to keep making copies of the string, this would be super inefficient. This is sort of a design
choice that was made by C. (There are actually deeper reasons behind this, but let’s leave it at that for now…)

(Usability from the perspective of the function caller) Think about strtol() and how
it kind of had to return two things for us: (1) the converted value, if any, and (2) where it stopped trying to convert.

Having pointers means function callers can now pass in addresses of variables so that the called function can say “ah we go here to set your return value”.
Look back at how strtol() would do this to a pointer we have.

(Dynamic memory allocation) Lastly, you should have seen malloc/calloc etc by now. Ever notice how
we only get access to them via pointers? Here’s something for contrast: Local variables declared by functions usually have names.
Their names are how we refer to them, and access them. The issue with items on the heap is that these are often created at runtime.
When we ask malloc for an allocated region of memory, we can’t name it. The best we have is the address of where it is. In other words,
we really only have pointers to dynamically allocated objects.