Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, of course: the pointer is guaranteed to be aligned in the first case (by §5.3.4/10 and §3.7.4.1/2), and may be correctly aligned in both cases. (Obviously, if <code>sizeof(int) == 1</code>, but even when this is not the case, an implementation doesn't necessarily have alignment requirements.) </p> <p>And to make things clear: your casts are all <code>reinterpret_cast</code>.</p> <p>Beyond that, this is an interesting question, because as far as I can tell, there is no difference in the two casts, as far as the standard is concerned. The results of the conversion are unspecified (according to §5.2.10/7); you're not even guaranteed that converting it back into a <code>char*</code> will result in the original value. (It obviously won't, for example, on machines where <code>int*</code> is smaller than a <code>char*</code>.)</p> <p>In practice, of course: the standard requires that the return value of <code>new char[N]</code> be sufficiently aligned for any value which may fit into it, so you are guaranteed to be able to do:</p> <pre><code>intPtr = new (charPtr) int; </code></pre> <p>Which has exactly the same effect as your cast, given that the default constructor for <code>int</code> is a no-op. (And assuming that <code>sizeof(int) &lt;= 42</code>.) So it's hard to imagine an implementation in which the first part fails. You should be able to use the <code>intPtr</code> just like any other legally obtained <code>intPtr</code>. And the idea that converting it back to a <code>char*</code> would somehow result in a different value from the original <code>char*</code> seems preposterous.</p> <p>In the second part, all bets are off: you definitely can't dereference the pointer (unless your implementation guarantees otherwise), and it's also quite possible that converting it back to <code>char*</code> results in something different. (Imagine a word addressed machine, for example, where converting a <code>char*</code> to an <code>int*</code> rounds up. Then converting back would result in a <code>char*</code> which was <code>sizeof(int)</code> higher than the original. Or where an attempt to convert a misaligned pointer always resulted in a null pointer.)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload