1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

void print_array(const void* const* array, int size, void (*print_fn)(const void*)) {
    for(int i = 0; i < size; i++) {
        print_fn(array[i]);
        fputc('\n', stdout);
    }
}

void print_string(const void* a_data) {
    const char* str = a_data;
    fputs(str, stdout);
}

void print_integer_in_decimal(const void* a_data) {
    const int* a_num = a_data;
    printf("%d", *a_num);
}

void print_integer_in_hexadecimal(const void* a_data) {
    const int* a_num = a_data;
    printf("%x", *a_num);
}

void print_string_with_quotes(const void* a_data) {
    const char* str = a_data;
    fputc('"', stdout);
    fputs(str, stdout);
    fputc('"', stdout);
}
int main(int argc, char* argv[]) {
    // in order to call our print logic, need to declare this as void*
    const void* strings[] = {
        "Hello",
        "World",
        "Generic",
        "Addresses %s"
    };
    print_array(strings, 4, print_string);
    print_array(strings, 4, print_string_with_quotes);

    int numbers[] = { 9, 7, 4, 18, 100 };
    // to pass in numbers, we had to copy it into a void* array
    const void* numbers_as_void[5];
    for(int i = 0; i < 5; i++) {
        numbers_as_void[i] = numbers + i;
    }
    print_array(numbers_as_void, 5, print_integer_in_decimal);
    print_array(numbers_as_void, 5, print_integer_in_hexadecimal);


    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2024 Alexander J. Quinn & David Burnett         This content is protected and may not be shared, uploaded, or distributed.