Before This Lab: Pointer Primer

We highly recommend that you do our A Primer on Pointers (Part 1) before this lab to get a bit more practice. You can run the code for that directly within our CS1010 site!

Preface

It was a little hard to decide what exactly we should be covering in this lab itself. Because there are many good and useful techniques related to pointers and also strings. So we will mostly make it a mix of both.

Don’t take this to be a be-all-end-all list of “programming tricks”. Rather it’s a small taster of the kind of approaches you might take. We’ve picked out the ones that might have the best “carryover” potential but this is by no means an exhaustive list.

  1. We’ll start with a few quirks about pointers that we could not spend more time on in the lecture (though if you had paid attention, these should be easy to answer)
  2. We’ll show a few programs that actually make use of pointer manipulations naturally in your code

Get Started

Download the Lab 6 code through Entainer and open a terminal in the Lab 6 directory

Each activity has its own directory and Makefile

Run make inside the activity directory to compile its program, and run it again after editing

For Activity 3 (after repair), Activities 5 and 6, and Problem Solving Practice 1, run make test to check the public cases


Pointer Mechanics/Quirks

Activity 1: Incrementing Pointers

#include <stdio.h>
#include <stddef.h> // include for size_t
 
void print_arr(int arr[], size_t len){
	for(size_t idx = 0; idx < len; ++idx){
		printf("%d,", arr[idx]);
	}
	printf("\n-----\n");
}
 
void foo(int *arr){
	++arr;
	printf("foo: %d\n", *arr);
}
 
void bar(int *arr){
	++*arr;
    printf("bar: %d\n", *arr);
}
 
void qux(int *arr){
	*arr++;
    printf("qux: %d\n", *arr);
}
 
void corge(int *arr){
    (*arr)++;
    printf("corge: %d\n", *arr);
}
 
int main(){
	int arr[5] = {2, 4, 6, 21, 400};
	foo(arr);
	print_arr(arr, 5);
	bar(arr);
	print_arr(arr, 5);
    qux(arr);
	print_arr(arr, 5);
    corge(arr);
	print_arr(arr, 5);
}

In the above code, we have functions foo, bar, qux, corge. Each with a slightly different definition that intermixes the ++ and * operators.

In activity-1, run make, then ./pointer-increments

Read the printed output and figure out what each function does to the pointer and the elements it points to

Activity 2: Sizing for Arrays

Open activity-2/main.c.
Run make, then ./array-size.

#include <stdio.h>
 
void foo(int arr[]){
	printf("foo: %zu\n", sizeof(arr));
}
 
int main(){
	int arr[5] = {2, 4, 6, 21, 400};
	printf("main: %zu\n", sizeof(arr));
	foo(arr);
}

Part 1:

Compile the code. Are there any warnings? If any, what is the warning about? Why do you think that warning is happening?

Part 2:

Run the code, and check the output. Does this match your expectations? Try to explain why the output is the way it is.

Activity 3: String Literals Are Special

Open activity-3/main.c.
We’re going to pick up where we left off from the lecture and explore a little more about string literals.

#include <stdio.h>
 
int main(){
   char *p = {'a', 'b', 'c', '\0'};
   char s[] = {u8'a', u8'b', u8'c', u8'\0'};
   char *t = "abc";
   char r[3] = "abc";
   printf("%s\n", r);
}

Part 1:

Run make in activity-3

This first build is expected to fail

Which lines cause errors? What are the errors about?

Part 2:

Remove or comment out the line(s) that are causing errors and recompile

Are there warnings now?

Run ./string-literals. Is the output what you expected?

Read the sanitiser report. What do you think happened?

Part 3:

What should you do to fix the program so that it works now?

Rebuild, then run ./string-literals and make test

Activity 4: Pointer Arithmetic

Open activity-4/main.c.

#include <stdio.h>
 
int main(){
   char arr1[] = "asdf";
   int arr2[] = {2, 3, 5, 9};
 
	printf("address of arr1[0]: %p\n", arr1);
	printf("address of arr1[1]: %p\n", arr1 + 1);
	printf("address of arr2[0]: %p\n", (void *)(arr2));
	printf("address of arr2[1]: %p\n", (void *)(arr2 + 1));
}

Note that (void *) is also a valid way of converting a pointer so that printf’s %p can print it. In fact, (void *) is the only conversion that works for this purpose before C23.

In activity-4, run make, then ./pointer-addresses

Explain the differences between consecutive addresses of elements of arr1 and arr2

Reminder

In the hexadecimal system, the digits go from 0 through 9, then A through F before “wrapping back” around to 0.


Pointer Manipulations

Activity 5: Iterating “Forwards” with Recursion

You might remember how we summed up all the elements in an array recursively, an example snippet below:

#include <stddef.h>
 
int sum_arr(int arr[], size_t len){
	if(len == 0){
		return 0;
	}
 
	return arr[len - 1] + sum_arr(arr, len - 1);
}

There’s nothing wrong with it, but it can be seen as very slightly awkward for some.
Each recursive call removes the last element from the remaining problem.
Turns out, we can use pointer arithmetic for a succinct solution that removes the first element instead.

Part 1

#include <stddef.h>
 
int sum_arr(int arr[], size_t len){
	if(len == 0){
		return 0;
	}
	return arr[0] + sum_arr(???, len - 1);
}

Your task: Figure out what exactly you should write in the ???. It might help to recall that arr is a pointer, and you should use pointer arithmetic.

Part 2

#include <stdio.h>
#include <stddef.h>
 
void print_arr(int arr[], size_t len){
 
}

Now instead, write a recursive function that prints from the first to the last element (in that order).
The idea is to use a similar trick as Part 1.
This way you don’t actually need to make helper functions, which is a lot cleaner.

Implement sum_arr and print_arr in activity-5/student.c

Print each element preceded by one space; main.c prints the label and final newline

An empty array has sum 0 and prints no elements

Use recursion and pointer arithmetic, without a loop or helper function

Run make, then ./forward-recursion, and enter an element count followed by the elements on the next line

Run make test to check both the sum and the printing order

The count is between 0 and 100.
Each value is between INT_MIN / 100 and INT_MAX / 100, so every partial sum fits in an int.

Activity 6: Pointers as Iterators

Building on the previous part, let’s also see how iterators can be used in loops.

Part 1

Let’s say we wanted to iterate on a string and count how many alphabetical characters there were. Here’s a simple for loop that would do that for you:

#include <ctype.h> // included for isalpha
#include <string.h> // included for strlen
#include <stddef.h> // include for size_t
 
unsigned int num_alphabetical(char const *str){
	size_t length = strlen(str);
	unsigned int count = 0;
	for(size_t idx = 0; idx < length; ++idx){
		count += ( isalpha((unsigned char)str[idx]) ) ? 1 : 0 ;
	}
	return count;
}

Notice that we don’t actually use the pointer str for anything aside from accessing the characters. We can actually alter the pointer itself.

unsigned int num_alphabetical(char const *str){
	unsigned int count = 0;
	while(<termination condition>){
		// loop body
	}
	return count;
}

Your task: Figure out and write the termination condition and loop body so that it uses only the str pointer and the count variable.

Part 2

void redact(char *str){
	// Your code here
}

Your task: Given a string, transform any non-space characters into the * character.
Here, space means ' ', not a tab or other whitespace character.
Again, you should find a way to only use the str pointer itself to accomplish your task.

Implement num_alphabetical and redact in activity-6/student.c

Run make, then ./string-iterators, and enter one line of text

Run make test to check both functions, including empty strings and spaces

The program accepts a line of up to 4,094 bytes, excluding its final newline,
and uses the C locale for classifying characters.


Problem Solving Practice 1: Where Pointers Crop Up in the Wild

Let’s end on a problem solving question that shows a natural use-case for pointers, string to integer conversion.

Attempt String to Integer in Volume 6