E
Eric Laberge
Hi!
I'm working on automatically generated code, and need to assign arrays.
memcpy is an obvious solution, but it becomes complicated to use in the
context I'm working on, ie.: I could use it but I don't want to.
Arrays cannot be assigned in C, but structs can, so I coded the
following:
#include <stdlib.h>
int main(void)
{
void* a = malloc(10); /* This obviously should be checked for malloc
failure */
void* b = malloc(10); /* This too... */
*((struct copy {unsigned char t[10];}*) a) = *((struct copy*) b);
free(a);
free(b);
return 0;
}
I wouldn't have tought that this would compile, let alone not give a
single warning (gcc -W -Wall -pedantic). It even works , as I tried
copying and displaying a string. I can easily code that in my code
generator (a translator, actually) and I suppose it would even let me
cast expressions to an array!
What I'm wondering, since this is not too bad looking as a solution,
is:
1) Is this solution common?
2) Is this portable?
3) Does this actually respects the C standard? (if not, why?)
4) Any way to improve this assign without using a function?
FYI, I tried using anonymous structures:
*((struct {unsigned char t[10];}*) a) = *((struct {unsigned char
t[10];}*) b);
but the compiler complained about incompatible types, which I
understand the cause. I had to try it, though.
Thanks
I'm working on automatically generated code, and need to assign arrays.
memcpy is an obvious solution, but it becomes complicated to use in the
context I'm working on, ie.: I could use it but I don't want to.
Arrays cannot be assigned in C, but structs can, so I coded the
following:
#include <stdlib.h>
int main(void)
{
void* a = malloc(10); /* This obviously should be checked for malloc
failure */
void* b = malloc(10); /* This too... */
*((struct copy {unsigned char t[10];}*) a) = *((struct copy*) b);
free(a);
free(b);
return 0;
}
I wouldn't have tought that this would compile, let alone not give a
single warning (gcc -W -Wall -pedantic). It even works , as I tried
copying and displaying a string. I can easily code that in my code
generator (a translator, actually) and I suppose it would even let me
cast expressions to an array!
What I'm wondering, since this is not too bad looking as a solution,
is:
1) Is this solution common?
2) Is this portable?
3) Does this actually respects the C standard? (if not, why?)
4) Any way to improve this assign without using a function?
FYI, I tried using anonymous structures:
*((struct {unsigned char t[10];}*) a) = *((struct {unsigned char
t[10];}*) b);
but the compiler complained about incompatible types, which I
understand the cause. I had to try it, though.
Thanks