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.
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)
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
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:
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.
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.
Note
If you had paid attention in lectures this part should be trivial but considering it’s such an important pattern I can’t risk people missing this. So if you didn’t listen in the lecture you’re gonna have to follow-up now lul.
- Eldon
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_tunsigned 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;}
Character Classification
isalpha returns zero for false and a nonzero value for true, which need not be 1.
We can also write:
count += isalpha((unsigned char)str[idx]) != 0;
isalpha accepts an integer value representable as unsigned char, or EOF.
The (unsigned char) cast keeps a byte from the string in that accepted range.
Plain char can be signed, so some input bytes would otherwise become negative values.
The same rule applies when calling isspace on a character from a string.
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.