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.
struct CircularBuffer {
int E;
int S;
int length; // total number of item allowable in the buffer
int sizeOfType; // size of each element in the buffer
void *buffer;
};
struct CircularBuffer* circularBufferInit(int length, int sizeOfType) {
struct CircularBuffer *cb = malloc(sizeof(struct CircularBuffer));
cb->E = 0;
cb->S = 0;
cb->length = length;
cb->sizeOfType = sizeOfType;
cb->buffer = malloc(sizeOfType *length);
return cb;
}
int circularBufferIsEmpty(struct CircularBuffer* cb) {
if (cb->S == cb->E)
return 1; //empty
else
return 0;
}
int circularBufferIsFull(struct CircularBuffer *cb) {
int nE = (cb->E + 1) % (cb->length);
if (nE == cb->S)
return 1; //full
else
return 0;
}
void circularBufferAdd(struct CircularBuffer *cb, void* obj) {
memcpy(cb->buffer + cb->E, obj, cb->sizeOfType);
}
[...]
memcpy is the problem...
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.
来源:https://stackoverflow.com/questions/31734092/c-insert-get-element-in-from-void-array