C : Insert/get element in/from void array

前端 未结 1 1071
臣服心动
臣服心动 2021-01-29 11:00

I have to create a generic array that can contain generic data structures. How can i put a generic structure into an empty slot of my void array?

This is my code.

<
相关标签:
1条回答
  • 2021-01-29 11:58

    It seems that essentially you're trying to figure out how to offset a void * to the address of an array element of known size but unknown type so you can pass it to memcpy().

    It looks as though, in circularBufferAdd(), cb->E gives the index of the element you want to copy to, cb->buffer is the void * to the array, obj is the item to be copied, and cb->sizeOfType is the size each array element (and obj). In that case you can change:

        memcpy(cb->buffer + cb->E, obj, cb->sizeOfType);
    

    to:

        memcpy((char *)cb->buffer + (cb->E * cb->sizeOfType), obj, cb->sizeOfType);
    

    Since you can't use pointer arithmetic with a void *, you'd cast it to char *. Then, you can multiply the element index by the element size to get the offset of the element in bytes, and use that to get the address of the element you need.

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