Learn C With Me #13 — Pointers II, Part Two | Live

In Lesson 13 of Learn C With Me, we continue Chapter 11 — Pointers II from Beej’s Guide to C Programming, this time exploring one of C’s most interesting features: void pointers.

We learn how a pointer can refer to data without specifying its type, why generic pointers are useful, and how standard library functions such as memcpy() and qsort() can work with different kinds of data.

We cover:

  • What void * means in C
  • The difference between typed pointers and generic pointers
  • Why void * can point to different data types
  • Understanding generic functions
  • Using memcpy() to copy memory
  • Source and destination pointers
  • Understanding byte counts and size_t
  • Copying character arrays and other data
  • Why void * cannot be dereferenced directly
  • Why standard C doesn’t support arithmetic on void *
  • Converting generic pointers to typed pointers
  • Using casts when working with pointers
  • Understanding pointer types and memory representation
  • Returning pointers from functions
  • Why library functions often return void *
  • Introducing qsort()
  • Sorting arrays containing structs
  • Writing a comparison function
  • Why comparison functions receive const void * arguments
  • Converting those arguments to the appropriate pointer type
  • Sorting structs by one of their fields
  • Understanding the arguments passed to qsort()
  • How comparison results determine sorting order
  • Compiler errors, debugging and reading manual pages

One of the biggest challenges in this lesson is understanding how void * makes generic programming possible in C. A function such as memcpy() doesn’t need to know whether it is copying characters, integers or other data. It works with memory and a specified number of bytes.

We also discover the limitations of generic pointers. Since a void * doesn’t specify the pointed-to object’s type, we cannot simply dereference it or perform ordinary pointer arithmetic on it.

Later, we experiment with qsort(), sorting an array of animal structs by their number of legs. This introduces another important concept: passing a comparison function to a library function so it knows how to order our data.

As usual, we read the book, experiment, make mistakes, consult the manual pages, get help from the live chat, and try to understand why C works the way it does.

This stream completes our exploration of Pointers II.

Homework #13 — Void Pointers and qsort()

This week we’re going to experiment with generic programming in C.

In Lesson 13 of Learn C With Me, we explored void *, experimented with memcpy(), and discovered how the standard library’s qsort() function can sort different types of data.

Now it’s time to try it ourselves!

The goal is to practice what we’ve learned in Chapter 11 — Pointers II, without using concepts from later chapters.

1. Sort an array of integers

Start with:

int numbers[] = {42, 7, 100, 3, 25, 18};

Use qsort() to sort the array in ascending order.

Write a comparison function with this prototype:

int compare_ints(const void *a, const void *b);

Inside the function, convert the generic pointers to pointers to integers, then compare the values.

Remember that the comparison function should return:

  • A negative value if the first element comes before the second
  • Zero if both elements compare equal
  • A positive value if the first element comes after the second

Print the array before and after sorting.

Expected result:

Before: 42 7 100 3 25 18
After:  3 7 18 25 42 100

Question: Why does qsort() need a comparison function instead of simply knowing how to sort integers?

2. Reverse the sorting order

Modify your comparison function so that the same array is sorted in descending order.

Expected result:

100 42 25 18 7 3

Try to achieve this by changing only the comparison logic.

Question: Does qsort() itself need to change?

3. Sort an array of structs

Create the following struct:

struct animal {
    char *name;
    int legs;
};

Then create an array:

struct animal animals[] = {
    {"Spider", 8},
    {"Dog", 4},
    {"Snake", 0},
    {"Human", 2},
    {"Ant", 6}
};

Write a comparison function:

int compare_animals(const void *a, const void *b);

Use qsort() to sort the animals by their number of legs.

Expected result:

Snake: 0 legs
Human: 2 legs
Dog: 4 legs
Ant: 6 legs
Spider: 8 legs

This is similar to the example we explored during the stream.

Questions:

  • Why does the comparison function receive const void * rather than struct animal *?
  • How do we access the legs field through those pointers?
  • What does sizeof(struct animal) tell qsort()?

4. Experiment with memcpy()

Create two character arrays:

char source[] = "Learning C!";
char destination[50];

Copy the contents of source into destination using memcpy().

Print both strings.

Then experiment with the number of bytes being copied.

Important: Make sure the destination is large enough, and remember that C strings need their terminating '\0' byte.

Try copying the entire source array using:

sizeof source

Question: Why is sizeof source useful here?

5. Explore void pointers

Create:

int number = 42;
void *p = &number;

Try to print the value of number through p.

Can you directly write:

printf("%d\n", *p);

What does the compiler say?

Now convert the generic pointer to the appropriate type before dereferencing it.

For example:

int *typed = p;
printf("%d\n", *typed);

Try to explain why this works.

Bonus challenge — Sort by name

Return to the animal array.

Instead of sorting animals by their number of legs, sort them alphabetically by name.

You may use strcmp() from <string.h>, which we encountered when learning about strings.

Question: How can the same qsort() function sort animals by completely different criteria without changing its implementation?


Rules

Use only concepts covered in Learn C With Me, up to and including Chapter 11 — Pointers II.

You may use:

  • Arrays, strings and structs
  • Functions and function pointers as used with qsort()
  • Typed pointers and void *
  • memcpy()
  • qsort()
  • sizeof
  • Standard string functions already covered

You do not need:

  • malloc(), calloc() or realloc()
  • free()
  • Dynamic memory allocation
  • Any concepts from later chapters

What we’re practicing

The main idea is to understand how generic functions work.

qsort() doesn’t know whether it is sorting integers, structs or something else. It relies on information we provide:

  1. Where the array begins
  2. How many elements it contains
  3. How large each element is
  4. How to compare two elements

The comparison function provides the knowledge that qsort() doesn’t have.

And memcpy() works with raw memory, without needing to know the original data type.

As always, experiment.

Make predictions, compile the examples, change the code, read the compiler diagnostics, and try to understand what happens.

If you get stuck, post your code and questions in the forum thread.

i liked this how work this time AI did not make redundant parts or need to overwrite them so here is what i got

fancy code of secrets
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int numbers[] = {42, 7, 100, 3, 25, 18};
int original[6];

struct animal {
    char *name;
    int legs;
};

struct animal animals[] = {
    {"Spider", 8},
    {"Dog", 4},
    {"Snake", 0},
    {"Human", 2},
    {"Ant", 6},
    {"Unilateral amputee",1}
};
struct animal original_animals[6];

int compare_animals(const void *a, const void *b) {
    const struct animal *animal1 = a;
    const struct animal *animal2 = b;
    if (animal1->legs > animal2->legs) {
        return 1;
    }
    if (animal1->legs < animal2->legs) {
        return -1;
    }
    return 0;
}

int compare_animals_alpha(const void *a, const void *b) {
    const struct animal *animal1 = a;
    const struct animal *animal2 = b;
    return strcmp(animal1->name, animal2->name);
}

int compare_ints(const void *a, const void *b) {
    const int *num1 = a;
    const int *num2 = b;
    if (*num1 > *num2) {
        return 1;
    }
    if (*num1 < *num2) {
        return -1;
    }
    return 0;
}

int reverse_compare_ints(const void *a, const void *b) {
    const int *num1 = a;
    const int *num2 = b;
    if (*num1 < *num2) {
        return 1;
    }
    if (*num1 > *num2) {
        return -1;
    }
    return 0;
}

void reset_numbers(void) {
    memcpy(numbers, original, sizeof(numbers));
}

void reset_animal(void) {
    memcpy(animals, original_animals, sizeof(animals));
}

void printnum(void) {
    for (int i = 0; i < 6; i++) {
        printf(" %d", numbers[i]);
    }
}

void print_animals(void) {
    for (int i = 0; i < 6; i++) {
        printf("%s: %d legs\n", animals[i].name, animals[i].legs);
    }
}

int main(void) {
    memcpy(original, numbers, sizeof(numbers)); //coppy to original so i can reset numbers later
    memcpy(original_animals, animals, sizeof(animals)); //coppy for animals for reset
    
    printf("Qsort output\n");
    printf("Befor:");
    printnum();

    qsort(numbers, 6, sizeof(int), compare_ints);
    
    printf("\nAfter:");
    printnum();
    printf("\n\n");

    reset_numbers();
    
    printf("Reverse Qsort output\n");
    printf("Befor:");
    printnum();

    qsort(numbers, 6, sizeof(int), reverse_compare_ints);
    printf("\nAfter:");
    printnum();
    printf("\n\n");
    
    printf("Sorted animals by leg count\n");
    qsort(animals, 6, sizeof(struct animal), compare_animals);
    print_animals();
    reset_animal();
    printf("\n\n");

    printf("Sorted animals by name\n"); // bonus point! with extra compare func
    qsort(animals, 6, sizeof(struct animal), compare_animals_alpha);
    print_animals();
    reset_animal();
    printf("\n\n");

    printf("Destination data from source: ");
    char source[] = "Learning C!";
    char destination[50]; //if [] is bellow 13 '\0' will be lost breaking destination and the loop will run forever
    memcpy(destination, source, sizeof(source)); // think memcpy would complain if destination is to small
    int i = 0;
    while (destination[i] != '\0') {
        printf("%c", destination[i]);
        i++;
    }
    printf("\n");

    int number = 42;
    void *p = &number;
    printf("Dirrect pointer with (int *) to %d\n", *(int *)p); //had to int pointer cast it becuse %d dont use void pointer i think
    int *typed = p;
    printf("Pointer to pointer to %d\n", *typed);

    return 0;
}

picture for the brave who like spoilers

honestly this one fealt like a trail and error for me.

It was good practice actually.

Summary
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/*///////////
// Part 1
///////////*/

int compare_ints(const void *a, const void *b) {
	int i = *(const int*)a;
	int j = *(const int*)b;

	if (i < j)
		return -1;
	else if (i > j)
		return 1;
	else
		return 0;
}

/*///////////
// Part 2
///////////*/

int compare_ints_rev(const void *a, const void *b) {
	return compare_ints(b, a);
}


/*///////////
// Part 3
///////////*/

struct animal {
    char *name;
    int legs;
};

struct animal animals[] = {
    {"Spider", 8},
    {"Dog", 4},
    {"Snake", 0},
    {"Human", 2},
    {"Ant", 6}
};

int compare_animals(const void *a, const void *b) {
	const struct animal *aa = a;
	const struct animal *ab = b;
	return compare_ints(&aa->legs, &ab->legs);
}

/*///////////
// Part 4
///////////*/

void copy_strings(void) {
	char source[] = "Learning C!";
	char destination[50];

	memcpy(destination, source, 3);
	destination[3] = '\0';
	printf("`%s`\n", destination);

	// sizeof(source) includes the terminating 0-character
	memcpy(destination, source, sizeof(source));
	printf("`%s`\n", destination);
}

/*///////////
// Part 5
///////////*/

void void_pointer_derefs(void) {
	int number = 42;
	void *p = &number;
	// error: pointer to void can't be dereferenced.
	// printf("%d\n", *p);


	int *typed = p;
	// ok: `typed` is a pointer to int.
	printf("%d\n", *typed);
}

/*///////////
// Bonus
///////////*/

int compare_animals_total(const void *a, const void *b) {
	const struct animal *aa = a;
	const struct animal *ab = b;

	// dogs may have legs > 4
	int name_ord = strcmp(aa->name, ab->name);
	return name_ord != 0 ? name_ord : compare_ints(&aa->legs, &ab->legs);
}

i must say david in part 3 are you not comparing the ints of the address instead of leg count itself?
and kind of like your reverse ints just switched a and b XD
part 4 is confusing me a bit would destination print Lea or Lea’\0’rning C! ?

No, it takes the address of the leg count:

  const struct animal *aa = &a;
  &aa->legs
= &(aa->legs)
= &((*aa).legs)
= &(a.legs)

In part 4, after the first memcpy, destination is: {'L', 'e', 'a', ... 47 random bytes }.
Then the byte at index 3 is overwritten with '\0' (which is just the integer 0), so we have:
{'L', 'e', 'a', 0, ... 46 random bytes }
When seen as a C-string, destination is now equal to "Lea".

1 Like