I'm writing a dynamic array in C:
struct array {
int len;
int cap;
void *data;
};
It's easy to store values if I know the type:
void set(array* a, int idx, int val) {
((int*)a->data)[idx] = val;
}
But I want to accept any type (void*):
void set(array* a, int idx, void* val) {
a->data[idx] = val;
}
This obviously doesn't compile because 'void' is not assignable
As I understand, compiler needs information about the type to get its size and calculate the offset to access data.
Is there a way to do this on my own? Operate directly on bytes, something like
void set(array* a, int idx, void* val, int size) {
*((char*)a->data + size * idx) = val;
}
Basically I want to make them similar to Go slices. You can read about their built in generic types here:
https://dave.cheney.net/2018/05/29/how-the-go-runtime-implements-maps-efficiently-without-generics
No templates, no unboxing. They use void*
for data storage.