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>
#include <stdint.h>
void print_array(const void* array, int size, int num_elements, void (*print_fn)(const void*)) {
// ugly thing we have to do: cast the array to some random 1 byte element type
const uint8_t* byte_array = array;
for(int i = 0; i < num_elements; i++) {
// use the size to offset based on the index and the passed size
print_fn(byte_array + (size * i));
fputc('\n', stdout);
}
}
void print_string(const void* a_data) {
const char* const* a_str = a_data;
fputs(*a_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* const* a_str = a_data;
fputc('"', stdout);
fputs(*a_str, stdout);
fputc('"', stdout);
}
int main(int argc, char* argv[]) {
const char* strings[] = {
"Hello",
"World",
"Generic",
"Addresses %s"
};
// type of strings is char**
print_array(strings, sizeof(*strings), 4, print_string);
print_array(strings, sizeof(*strings), 4, print_string_with_quotes);
// type of numbers is int*
int numbers[] = { 9, 7, 4, 18, 100 };
print_array(numbers, sizeof(*numbers), 5, print_integer_in_decimal);
print_array(numbers, sizeof(*numbers), 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.