Casting pointers

Henry Spencer henry at zoo.toronto.edu
Tue Oct 2 04:14:06 AEST 1990


In article <1990Sep29.201144.23113 at maths.tcd.ie> tim at maths.tcd.ie (Timothy Murphy) writes:
>char *buf = "abc";
>  int *n = (int*) buf;
>  printf("%d", *n);
>Should this always work?
>On the Mac, with THINK C,
>it only works if buf has an even address. ...
>Is that a bug, according to standard C?

What you are doing is not portable, and your machine is quite entitled to
object to it.  Converting pointer-to-more-aligned-type to pointer-to-less-
aligned type (e.g. `int *' to `char *') is guaranteed to produce a usable
pointer, but not vice-versa.  You are working in the Twilight Zone of
undefined behavior, and all bets are off.
-- 
Imagine life with OS/360 the standard  | Henry Spencer at U of Toronto Zoology
operating system.  Now think about X.  |  henry at zoo.toronto.edu   utzoo!henry



More information about the Comp.std.c mailing list