B
Bernhard Holzmayer
Nishu said:Hi All,
Is it valid in C to typecast a pointer?
eg. code snippet... considering int as 16 bit and long as 32 bit.
int *variable, value;
*((long*)variable)++ = value;
*((long*)variable)++ = value;
*((long*)variable)++ = value;
*((long*)variable)++ = value;
Thanks,
Nishu
Minimalistic answer:
int *variable, value;
*( (int *)( ((long*)variable)++ )) = value;
*( (int *)( ((long*)variable)++ )) = value;
*( (int *)( ((long*)variable)++ )) = value;
*( (int *)( ((long*)variable)++ )) = value;
should work, provided that the address where variable points to,
has been initialized somewhere else.
Long answer:
Before assigning the value, the pointer should be cast back to the correct
type. (Implicit type propagation would do this for you, but that's not
desirable here.)
It will copy 'value' to four address locations with one int between,
which will not be updated. Only every 2nd address location will be written.
My guess: This is not what you want.
However, if you really intend this and would like to make this thing more
evident, you might want to use a structural method like this:
struct wr {
int a;
int b;
};
struct wr * variable; // again: memory must be defined somewhere!
int value;
now using
variable++>a = value;
variable++>a = value;
variable++>a = value;
variable++>a = value;
would result in the same effect, but is much more readable, avoids casts and
is much less error prone.
But keep in mind, that structures can contain additional management
components which aren't visible. So, the physical layout in memory might
differ or at least be machine dependent.
Bernhard