Re: pointer conversion



In article <_eidnezKNPZ67EXbnZ2dnUVZ_vShnZ2d@xxxxxxxxxxx>,
Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxxx> wrote:

M> You will be OK. char is always 1 byte. So casting an arbitrary
M> pointer to a char *, adding an exact multiple of the size of
M> the original type, and casting back is guaranteed to preserve
M> alignment.

I am not so sure about that; would you care to cite C&V, please, if
you claim that it's guaranteed by the standard?

He's wrong: it's not guaranteed. Simple example:

int target = 42;
int *ptr = &target + 1; /* "an arbitrary pointer" */
ptr = (int*)((char*)ptr + sizeof *ptr); /* U.B. */

If the original pointer points at an actual object of its
type (so it's not "arbitrary"), the conversion is safe.

That seems to be excessive pedantry. He said it "preserves
alignment", not that it's legal. Presumably you would deny that
adding 2 to an int preserves it odd/even parity, because you might
choose INT_MAX.

-- Richard

--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
.



Relevant Pages

  • Re: pointer conversion
    ... M> the original type, and casting back is guaranteed to preserve ... If the original pointer points at an actual object of its ... alignment", not that it's legal. ...
    (comp.lang.c)
  • Re: Narrow To Wide To Narrow String Conversion With reinterpret_cast
    ... |> It doesn't really matter if it is safe or not at this ... | '7 A pointer to an object can be explicitly converted to a pointer to ... | no stricter than those of T1) and back to its original type yields ...
    (alt.comp.lang.learn.c-cpp)
  • Re: multi dimensional arrays as one dimension array
    ... Where, in fact, does the standard say ... anything at all about what you can do with the converted pointer value, ... Pointer conversion yields a pointer to the same object as ... convert it back to the original type and compare it against ...
    (comp.lang.c)
  • Re: Narrow To Wide To Narrow String Conversion With reinterpret_cast
    ... > It doesn't really matter if it is safe or not at this ... '7 A pointer to an object can be explicitly converted to a pointer to ... an object of different type.11) Except that converting an rvalue of ... no stricter than those of T1) and back to its original type yields ...
    (alt.comp.lang.learn.c-cpp)
  • Re: contiguity of arrays
    ... >>The standard never says what the result of the conversion is,' ... Imagine a machine where the representation of a pointer has two extra ... When you convert &the_array to int*, the compiler turns ... When you convert it back to the original type, ...
    (comp.lang.c)