unsigned char buf[100] . . . unsigned int val; . . . val = *((unsigned int *)(&buf[1])); . . .
comments?
Yes, it is non-portable code. I can cause an alignment fault on some platforms.
been there, done that, and, even worse
Some compilers for 'multibyte word' processors that require alignment will not declare a fault but access the previous byte and the pointed byte instead of the pointed byte and the next. (I.e. a 16 bit processor that ignore LSB of the address for word fetch). When I complained about it to one compiler maker, I was informed "there is nothing in ANSI C about this". I never checked, what good does it do to state "there is something in ANSI C about this", if your program does not work because of such.
Then, of course, there are the endianness which, if the array is accessed both as char and int, will make a real pow-wow.
Erik (sorry abuot "multibyte word" what else would you call it)
Misalignment detection not really up to the compiler. Some hardware -- the ARM7/9 core for example -- doesn't even detect alignment faults, and will just silently do interesting things to your byte lanes.
There are some cases where compilers might be able to suspect or even prove alignnment problems, but I'm not sure that's possible in general, especially since actual positioning of the data is theoretically the job of the linker. Without inserting run-time checks on the actual value of a pointer just before it is used, which would have a huge effect on the code, I don't think a compiler can solve that problem in general. (Might make for an interesting debug option, just like an optional null pointer check that no compiler vendor offers as a debug option, either.)
sorry about "multibyte word"
Sounds good to me.
View all questions in Keil forum