> C doesn't have arrays#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef uint_least16_t FamType;
typedef struct Senpai {
size_t count;
uint_least16_t members[];
} Senpai;
size_t famSize(size_t count) { return sizeof(Senpai) + count * sizeof(FamType); }
int setFam(Senpai* senpai, FamType (*map)(int index)) {
if (senpai == NULL || senpai->count > INT32_MAX || map == NULL) return -1;
for (int idx = 0; idx < senpai->count; ++idx) senpai->members[idx] = map(idx);
return 0;
}
int makeFam(Senpai** famPtr, size_t count, FamType (*map)(int)) {
if (famPtr == NULL || map == NULL || count > INT32_MAX) return -1;
*famPtr = malloc(famSize(count));
if (*famPtr == NULL) return -2;
(*famPtr)->count = count;
if (setFam(*famPtr, map) != 0) free(*famPtr);
return 0;
}
int sumFam(Senpai* senpai, uint_fast32_t* sumPtr) {
if (senpai == NULL || senpai->count > INT32_MAX || sumPtr == NULL) return -1;
uint_fast32_t sum = 0;
for (int idx = 0; idx < senpai->count; ++idx) sum += senpai->members[idx];
*sumPtr = sum;
return 0;
}
FamType identity(int index) { return (FamType)index; }
FamType twoXplus1(int index) { return (FamType)(2 * index + 1); }
int main(void) {
Senpai* fam1 = NULL;
Senpai* fam2 = NULL;
int result = makeFam(&fam1, 13, identity);
if (result != 0) goto cleanup;
result = makeFam(&fam2, 42, twoXplus1);
if (result != 0) goto cleanup;
uint_fast32_t sum;
if ((result = sumFam(fam1, &sum)) != 0) goto cleanup;
printf("Size of fam1 = %zu, sum = %lu\n", famSize(fam1->count), sum);
if ((result = sumFam(fam2, &sum)) != 0) goto cleanup;
printf("Size of fam2 = %zu, sum = %lu\n", famSize(fam2->count), sum);
cleanup:
free(fam1);
free(fam2);
return result;
}
One more c-hater lie and myth crossed off the books.