C : Insert/get element in/from void array

烈酒焚心 提交于 2019-12-02 13:17:53

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!