I am trying to implement a java like arraylist in C and now I am trying to make it generic. I am new to C and pointer arithmetic but I triedusing void* pointer for container, th
It looks like you're pretty close, but there were some issues with your add
function.
Since list
is a pointer you need list->numElements
not list.numElements
and the same for list->elementSize
. Also since you are only inserting one element, the third argument to memcpy
should just be list->elementSize
.
void add(ArrayList *list, void *input) {
if (list->numElements >= list->conSize) {
resize(list);
printf("resized\n");
}
memcpy((char*)list->con + list->numElements * list->elementSize, input, list->elementSize);
list->numElements++;
}
The resize
function looks almost correct, except that if realloc
fails it just returns. It should probably either error out or return a value indicating an error to the caller.