I think this is what you are trying to do.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define EXTEND_SIZE 256
typedef struct {
size_t count, el_size, alloc_count;
char data[];
} List;
List *List_new(size_t alloc_count, size_t el_size) {
List *list = malloc(sizeof *list + alloc_count * el_size);
if (list) {
list->count = 0;
list->el_size = el_size;
list->alloc_count = alloc_count;
}
return list;
}
bool List_add(List **list, void *data) {
if ((*list)->count >= (*list)->alloc_count) {
List *swap = realloc(*list, sizeof **list +
((*list)->alloc_count + EXTEND_SIZE) * (*list)->el_size);
if (!swap)
return false;
*list = swap;
(*list)->alloc_count += EXTEND_SIZE;
}
memcpy((*list)->data + (*list)->count * (*list)->el_size, data,
(*list)->el_size);
(*list)->count++;
return true;
}
int main() {
List *list = List_new(2, sizeof(int));
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (size_t i = 0; i < sizeof a / sizeof *a; ++i)
if (!List_add(&list, &a[i])) {
printf("Problem reallocating memory.\n");
return EXIT_FAILURE;
}
for (size_t i = 0; i < list->count; ++i)
printf("%d ", ((int*)list->data)[i]);
putchar('\n');
free(list);
return 0;
}