This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
sys_prog/func_pointers/collection.c
2019-11-04 11:49:21 +01:00

51 lines
867 B
C

#include <stdio.h>
#include <stdlib.h>
struct collection {
int* values;
size_t size;
size_t capacity;
};
void collection_print(struct collection * c, void(*f)(int)) {
for (size_t i = 0; i < c->size; i++) {
(*f)(c->values[i]);
}
}
struct collection * new_random_collection() {
struct collection* new = malloc(sizeof(struct collection));
if (!new) {
return NULL;
}
new->size = 50;
new->capacity = 100;
new->values = malloc(new->capacity * sizeof(int));
if (!new->values) {
free(new);
return NULL;
}
for (size_t i = 0; i < new->size; i++) {
new->values[i] = rand();
}
return new;
}
void collection_delete(struct collection *c) {
free(c->values);
free(c);
}
void pretty_print(int b) {
printf("%d, ", b);
}
int main() {
struct collection* c;
c = new_random_collection();
collection_print(c, pretty_print);
collection_delete(c);
}