Making a generic ArrayLIst in C

前端 未结 1 1524
一向
一向 2021-01-27 11:55

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

相关标签:
1条回答
  • 2021-01-27 12:29

    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.

    0 讨论(0)
提交回复
热议问题