H
Harald van =?UTF-8?B?RMSzaw==?=
Peter said:I don't think it does. If you think float and int variables are somehow
special, use malloced memory instead:
The rules for dynamically allocated memory are different. Dynamically
allocated memory gets its effective type from whatever data is stored in
it, while declared objects get their effective types from the declarations.
void *p1, *p2;
float *fp;
int *ip;
assert(sizeof (int) == sizeof (float));
p1 = malloc(sizeof (float));
p2 = malloc(sizeof (int));
fp = p1;
ip = p2;
*fp = 42.0;
*fp now has an effective type of float.
memcpy(p2, p1, sizeof (float));
For dynamically allocated memory (but only for that!), memcpy copies the
effective type of *fp to *ip...
/* do something with *ip */
....and if you actually do something with *ip here, you're using an lvalue of
type int to read something which has float as its effective type, meaning
the behaviour is not defined by the C standard.
If you had not used malloc, the effective type of int would have been
preserved, because a declared object cannot have its effective type
altered.
memcpy(p1, p2, sizeof (float));
How is this different from
p1 = malloc(sizeof (float));
fp = p1;
ip = p1;
*fp = 42.0;
/* do something with *ip */
?
For dynamically allocated memory, there is no difference.
You are accessing memory with the same content the same way. If the
sizeof (float) bytes pointed to by p1 are a float which cannot be
accessed as an integer after the assignment (*fp = 42.0), so are the
sizeof (float) bytes pointed to by p2 after the first memcpy.
Correct, but this isn't about "a float which cannot be accessed as an
integer". It is already stated as an implementation detail that a float
_can_ be accessed as an integer. This is about how to access it without
violating C's aliasing rules.