Learn C With Me #12 — Pointers II, Part One | Live

In Lesson 12 of Learn C With Me, we return to one of the most important concepts in C programming: pointers.

Using Beej’s Guide to C, we begin Chapter 11 — Pointers II: Arithmetic, exploring how pointer arithmetic works, how pointers relate to arrays, and why seemingly different expressions can access exactly the same data in memory.

We cover:

  • Pointer arithmetic in C
  • Adding integers to pointers
  • Why p + 1 doesn’t necessarily mean adding one byte
  • How pointer arithmetic depends on the pointed-to type
  • Using sizeof to understand memory offsets
  • Accessing array elements through pointers
  • Dereferencing expressions such as *(p + 1)
  • Changing pointers with p++
  • Moving through arrays without using indexes
  • Using a sentinel value to terminate a loop
  • Subtracting pointers
  • Finding the distance between two pointers
  • Using pointer subtraction to calculate string lengths
  • Why pointer subtraction requires pointers into the same array
  • Array/pointer equivalence
  • Understanding a[b] and *(a + b)
  • Accessing arrays using both pointer and array notation
  • Why a pointer variable can move but an array name cannot
  • Passing arrays and pointers to functions
  • Understanding char * function parameters
  • Experimenting with incorrect parameter types
  • Compiler warnings and incompatible arguments

One of the most interesting discoveries is that pointer arithmetic operates in elements, not individual bytes. When we add one to an int *, the resulting pointer advances by the size of an integer.

We also experiment with pointer subtraction and discover how it can be used to calculate the length of a string by finding the difference between two pointers.

Later, we explore array/pointer equivalence, including the relationship between a[i] and *(a + i). We revisit function parameters and experiment with what happens when we remove the pointer from a char * parameter.

As usual, we don’t just read the examples. We make predictions, write code, get confused, inspect compiler diagnostics, and work through the problems together with the live chat.

This is Part One of Pointers II. We continue the chapter in the next lesson, including void pointers.

Homework #12 — Pointers II: Arithmetic

This week we’re going to build a small Pointer Explorer program.

The goal is to practice what we learned in Chapter 11 — Pointers II: Arithmetic of Beej’s Guide to C Programming, up to Array/Pointer Equivalence.

We’ll explore how pointers move through arrays, how pointer arithmetic works, and how we can use pointers instead of array indexes.

1. Create an array

Start with:

int numbers[] = {10, 20, 30, 40, 50};

Create a pointer to its first element:

int *p = numbers;

Print the first element using:

*p

Then print the second element using:

*(p + 1)

Question: Why does adding 1 to p move to the next integer rather than the next byte?

2. Print the entire array using pointers

Write a loop that prints all five elements.

Do not use array indexing inside this loop.

Instead, use pointer arithmetic:

*(p + i)

Expected output:

10
20
30
40
50

Now rewrite the loop so that it increments the pointer itself:

p++;

Compare the two approaches.

What changes when you increment p?

What happens to the original array?

3. Use a sentinel value

Create another array:

int values[] = {11, 22, 33, 44, 55, 999};

The number 999 is our sentinel value.

Write a loop that prints the numbers until it encounters 999.

You must use:

while (*p != 999)

and move the pointer forward after each iteration.

Expected output:

11
22
33
44
55

The sentinel itself should not be printed.

Question: What happens if the sentinel is missing?

Think about this before experimenting. Make sure you understand why the loop must not read beyond the array.

4. Calculate a string length using pointers

Create a function:

int my_strlen(char *s);

It should calculate the length of a C string without calling strlen().

Use two pointers:

  • One pointing to the beginning of the string.
  • Another moving forward until it encounters '\0'.

Then subtract the pointers to calculate the number of characters.

Example:

printf("%d\n", my_strlen("Hello"));

Expected output:

5

Try the function with several strings, including an empty string.

Question: Why does subtracting the two pointers give us the length?

For this exercise, assume strings short enough that the result fits in int.

5. Array/pointer equivalence

Start with:

int a[] = {10, 20, 30, 40, 50};
int *p = a;

Print the third element in four different ways:

a[2]
p[2]
*(a + 2)
*(p + 2)

Do all four expressions produce the same result?

Now try this:

2[a]

Does it compile?

What does it print?

Try to explain why using the relationship between array indexing and pointer arithmetic.

6. Write a function that sums an array

Create:

int sum_array(int *p, int count);

The function should return the sum of all elements in an integer array.

Use pointer arithmetic rather than array indexing inside the function.

Example:

int numbers[] = {10, 20, 30, 40, 50};

int result = sum_array(numbers, 5);
printf("%d\n", result);

Expected output:

150

Then change the function parameter from:

int *p

to:

int p[]

Does the function still work?

What does this tell us about arrays passed to functions?


Bonus challenge — Reverse an array

Create:

void reverse_array(int *p, int count);

Reverse the array in place, without creating another array.

For example:

Before: 10 20 30 40 50
After:  50 40 30 20 10

Use two pointers:

  • One starting at the beginning.
  • One starting at the last element.

Swap the values they point to, then move the pointers toward each other.

Stop when they meet or cross.

You may use a temporary integer variable to perform the swap.

Bonus challenge — Pointer addresses

Print the addresses of all elements in an integer array using %p.

Remember to convert the pointer to void * for %p, as covered in our earlier pointers lesson.

Observe the difference between consecutive addresses.

Then compare that difference with:

sizeof(int)

Try the same experiment with a char array.

Question: Why do pointers to different types advance by different numbers of bytes?


Rules

Use only concepts covered in Learn C With Me so far, up to the material we reached in Chapter 11.

You may use:

  • Variables and basic types
  • Loops and conditions
  • Functions
  • Arrays and strings
  • Pointers
  • Pointer arithmetic
  • Structs and typedef from earlier lessons

You do not need:

  • Dynamic memory allocation
  • malloc() or free()
  • Generic void * pointers
  • Concepts from later chapters

What we’re practicing

The most important relationship in this homework is:

a[i] == *(a + i)

We want to understand why those expressions are equivalent, not simply memorize them.

Also remember that pointer arithmetic is only valid within the appropriate array bounds, including the one-past-the-end position, which must not be dereferenced.

As always, experiment, make predictions, compile the code, and compare your expectations with the results.

If something doesn’t work, post your code and compiler diagnostics in the forum thread.

one thing is that these AI homeworks wants you to awnser questions and rewrite the code so i just ignored the questions and made 1 file with out rewriting it and just doing bouth at the same time

code of secrets
#include<stdio.h>


int my_strlen(char *s) {
    char *original = s;
    if (s == "") {
        return 0;
    }
    while (*s != '\0') {
        s++;
    }
    return s - original;
}

int sum_array(int *p, int count) {
    int *original = p;
    int sum = 0;
    if (count <= 0) {
        return sum;
    }
    while ((p - original) != count) {
        sum += *p;
        p++;
    }
    return sum;
}

void reverse_array(int *p, int count) {
    if (count <= 1) {
        return;
    }
    int *start = p;
    int *end = p + count -1; //excludes teminator symbol i think
    while (start < end) { //dose not run wen in the middel so its untouched
        int tmp = *start; // temp to save the start so we dont ower write it
        *start = *end;
        *end = tmp; // adds the first one to the end
        start++; //shuld increment closer to midle
        end--; //shuld decrement closer to middle
    }
}

int main(void) {
    int numbers[] = {10, 20, 30, 40, 50};
    int *p = numbers;
    int *original = p; //saves start location of p in original
    printf("First element: %d\n", p[0]);
    printf("Second element: %d\n", *(p + 1));
    printf("Pointer loop of the array\n");
    int counter = 0;
    
    for (;counter < 5;) {
        // counted at 1 instead of 0 becuse \/ of human counting
        printf("Array element %d: %d\n", counter + 1, *(p + counter++));
    }
    counter = 0; //counter reset for later use
    printf("Pointer loop with p++\n");
    
    for (;;p++) {
        printf("Array elemnt %d: %d\n", counter + 1, *(p));
        if (*p == 50) {
            break;
        }
    }
    p = original; //pointer reset to start of array
    // spent 30 min realise that i was using capital P to reset it witch ofc was not declared XD
    counter = 0;
    
    int values[] = {11, 22, 33, 44, 55, 999};
    //p = original + 8;
    //moves pointer to start of values becuse numbers is 5 bytes + 3 zerod out bytes becuse of int decleration i think
    p = values; // nvm i am stupid
    printf("While loop with sentinel value\n");
    while (*p != 999) {
        printf("Array element %d: %d\n", counter + 1, *(p++));
        counter++;
    }
    counter = 0;
    
    printf("String length with my_strlen function\n");
    printf("Length of string is: %d\n", my_strlen("Hello"));
    printf("Length of an empty string is: %d\n", my_strlen(""));
    
    int a[] = {10, 20, 30, 40, 50};
    p = a;
    printf("Third element with a[2] is: %d\n", a[2]);
    printf("Third element with p[2] is: %d\n", p[2]);
    printf("Third element with *(a + 2) is: %d\n", *(a + 2));
    printf("Third element with *(p + 2) is: %d\n", *(p + 2));

    printf("Sums numbers in the array\n");
    p = numbers;
    int result = sum_array(numbers, 5);
    printf("Total sum is: %d\n", result);
    result = sum_array(numbers, 2);
    printf("Total sum is: %d\n", result);
    //bonus time
    printf("Reversed array + Addresses\n");
    reverse_array(numbers, 5);
    for (int i = 0; i < 5; i++) {
        printf("Arrayt element %d: value = %d, address = %p\n", counter + 1, *(p + i), p + i);
        counter++;
    }

    return 0;
}
picture of secrets

pritty sure i missunderstood part 5 but might be what it asked for

seams i made a misstake i forgot to reset or start at 1 on pointer loop so it went 2-6 instead of 1-5 sens i did not want 0-4 to show,
oh seams i did reset and change pointer in reverse order so it started in the wrong place

fixed it
#include<stdio.h>


int my_strlen(char *s) {
    char *original = s;
    if (s == "") {
        return 0;
    }
    while (*s != '\0') {
        s++;
    }
    return s - original;
}

int sum_array(int *p, int count) {
    int *original = p;
    int sum = 0;
    if (count <= 0) {
        return sum;
    }
    while ((p - original) != count) {
        sum += *p;
        p++;
    }
    return sum;
}

void reverse_array(int *p, int count) {
    if (count <= 1) {
        return;
    }
    int *start = p;
    int *end = p + count -1; //excludes teminator symbol i think
    while (start < end) { //dose not run wen in the middel so its untouched
        int tmp = *start; // temp to save the start so we dont ower write it
        *start = *end;
        *end = tmp; // adds the first one to the end
        start++; //shuld increment closer to midle
        end--; //shuld decrement closer to middle
    }
}

int main(void) {
    int numbers[] = {10, 20, 30, 40, 50};
    int *p = numbers;
    int *original = p; //saves start location of p in original
    printf("First element: %d\n", p[0]);
    printf("Second element: %d\n", *(p + 1));
    printf("Pointer loop of the array\n");
    int counter = 0;
    
    for (;counter < 5;) {
        // counted at 1 instead of 0 becuse \/ of human counting
        printf("Array element %d: %d\n", counter + 1, *(p + counter));
        counter++;
    }
    counter = 0; //counter reset for later use
    printf("Pointer loop with p++\n");
    
    for (;;p++) {
        printf("Array elemnt %d: %d\n", counter + 1, *(p));
        counter++;
        if (*p == 50) {
            break;
        }
    }
    p = original; //pointer reset to start of array
    // spent 30 min realise that i was using capital P to reset it witch ofc was not declared XD
    counter = 0;
    
    int values[] = {11, 22, 33, 44, 55, 999};
    //p = original + 8;
    //moves pointer to start of values becuse numbers is 5 bytes + 3 zerod out bytes becuse of int decleration i think
    p = values; // nvm i am stupid
    printf("While loop with sentinel value\n");
    while (*p != 999) {
        printf("Array element %d: %d\n", counter + 1, *(p++));
        counter++;
    }
    counter = 0;
    
    printf("String length with my_strlen function\n");
    printf("Length of string is: %d\n", my_strlen("Hello"));
    printf("Length of an empty string is: %d\n", my_strlen(""));
    
    int a[] = {10, 20, 30, 40, 50};
    p = a;
    printf("Third element with a[2] is: %d\n", a[2]);
    printf("Third element with p[2] is: %d\n", p[2]);
    printf("Third element with *(a + 2) is: %d\n", *(a + 2));
    printf("Third element with *(p + 2) is: %d\n", *(p + 2));

    printf("Sums numbers in the array\n");
    p = numbers;
    int result = sum_array(numbers, 5);
    printf("Total sum is: %d\n", result);
    result = sum_array(numbers, 2);
    printf("Total sum is: %d\n", result);
    //bonus time
    printf("Reversed array + Addresses\n");
    reverse_array(numbers, 5);
    for (int i = 0; i < 5; i++) {
        printf("Arrayt element %d: value = %d, address = %p\n", counter + 1, *(p + i), p + i);
        counter++;
    }

    return 0;
}
picure after the fix

finally XD

That won’t work as you expect. You’re not comparing string to empty string, you’re comparing pointer s with pointer to wherever compiler put "" string literal.

If you want to check if string is empty the fastest way is to check first symbol: if (s[0] == '\0').

But it’s not really needed here anyway because there won’t be much extra work with empty string even if you drop that if statement: while loop will iterate 0 times as its condition will be false immediately.

but on an empty char array would s not be “”? or is it ‘\0’ as empty?

Empty string "" is an array of 1 element: the terminating '\0' character. All C strings end with '\0' and empty string is not an exception.

1 Like

Task 1:

#include <stdio.h>

int main(void){
  int numbers[] = {10, 20, 30, 40, 50};
  int *p = numbers;

  printf("1a: %d\n", *p);
  printf("1b: %d\n", *(p+1));
  // Adding 1 to p moves to the next integer because *p point to the first element and it knows the sizeof the int
}

Task 2a:

#include <stdio.h>

int main(void){
  int numbers[] = {10, 20, 30, 40, 50};
  int *p = numbers;

  int i;
  for (i=0; i<5; i++){
    printf("2a: %d\n", *(p+i));
  }
}

Task 2b: I segfaulted this and wrongly thought it should segfault. I will fix it later.

Task 3:

#include <stdio.h>

int main(void){
  int values[] = {11, 22, 33, 44, 55, 999};
  int *p = values;

  while (*p != 999){
    printf("3a: %d\n",*(p++));
  }
//if the sentinel would be missing then there would be no end to this while loop and we would start reading random memory and likely crash
}

I got stuck at 4. I did not look at the book at all, figured I will solve it from 100% memory from two weeks ago. I will post the rest here when I figure it out.