I have an array of arbitrary values, so I have defined it as an array of void pointers, so I can point to any kind of information (like int
, character arrays, etc). However, how do I actually assign an int
to it?
Take for example these initializations:
void* data[10];
int x = 100;
My intuition would think this, but this gives a compile error:
data[0] = malloc(sizeof(int));
*(data[0]) = x;
Also I thought about using &x
, but I would take the address of a local variable, which (to my understanding) would be cleared after exiting from the procedure. So if I have a local variable x
, how would I get it into a void pointer type of variable correctly?
*((int*)data[0])=x;
will do it.
You might want to consider using a union. Something like this:
union myvalues
{
int i;
double d;
long l;
};
You could then have
union myvalues *foo[10];
foo[0] = malloc(sizeof(union myvalues));
foo[0]->i = x;
You can also typedef
the union. sizeof(union myvalues)
will be the maximum of sizeof
the members. So if you have int i;
and char c[40]
in the union, sizeof(union myvalues)
will be 40. Writing to i
will then overwrite the first 4 characters in c
(assuming your ints are 4 bytes).
for aliasing reasons its far better to do
mempcy( data[0], &x, sizeof( int ) );
As it happens the compiler will optimise the memcpy call out as sizeof( int ) is a constant value but it won't break various aliasing rules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With