Can I cast a variable to a type decided during execution (?)
Yes, in some cases that support variable length array.
(double (*)[r])
is a cast to a type determined at run time. Demonstrative code follows:
int r = rand();
double a[r];
double (*b)[r] = &a;
unsigned char *data = malloc(sizeof a);
b = data; // warning: assignment to 'double (*)[r]' from incompatible pointer type 'unsigned char *' [-Wincompatible-pointer-types]
b = (double (*)[r]) data; // OK
(void) b;
In OP's code, the cast nor the sizeof(type)
are not needed.
Use target->val = realloc(target->val, target->length * sizeof(target->val[0]));
for both.
Only difference remaining in push_back_...()
is the function name and signature.
Is there any way that I can hold a variable to replace the cast to int*
or float*
so that i can reuse the same code for multiple variable types using void*
.
Any object pointer can be held in a void *
. Yet that void *
does not certainly retain anything to denote the type from which it is assigned. Auxiliary data needed. In OP's case, the size of the type would be enough if the size was consistent per vector.
typedef struct {
size_t object_size;
size_t length;
void *val;
} gVector;
// Pass in the address of the object to push
void* push_back_g(gVector* target, const void *push) {
void *p = realloc(target->val, target->object_size * (target->length + 1u));
if (p) {
target->val = p;
return memcpy((unsigned char *)val + target->object_size * target->length++,
push, target->object_size);
}
// Handle error with TBD code
return NULL;
}
Alternative we could pass in the size per push call and store that too.
Yet in both cases, code loses type checking.
With _Generic
, code could handle various pre-determined select types with common code. Yet it seems OP wants any type.