Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>From ANSI-ISO-IEC 14882-2003, p.87 (c++03): </p> <blockquote> <p>"75) Another way to approach pointer arithmetic is first to convert the pointer(s) to character pointer(s): In this scheme the integral value of the expression added to or subtracted from the converted pointer is first multiplied by the size of the object originally pointed to, and the resulting pointer is converted back to the original type. For pointer subtraction, the result of the difference between the character pointers is similarly divided by the size of the object originally pointed to."</p> </blockquote> <p>This seems to suggest that the pointer difference equals to the object size.</p> <p>If we remove the UB'ness from incrementing a pointer to a scalar a and turn a into an array:</p> <pre><code>int a[1]; size_t size_of_int = (char*)(a+1) - (char*)(a); std::cout&lt;&lt;size_of_int;// or printf("%zu",size_of_int); </code></pre> <p>Then this looks OK. The clauses about alignment requirements are consistent with the footnote, if alignment requirements are always divisible by the size of the object.</p> <p><strong>UPDATE:</strong> Interesting. As most of you probably know, GCC allows to specify an explicit alignment to types as an extension. But I can't break OP's "sizeof" method with it because GCC refuses to compile it:</p> <pre><code>#include &lt;stdio.h&gt; typedef int a8_int __attribute__((aligned(8))); int main() { a8_int v[2]; printf("=&gt;%d\n",((char*)&amp;v[1]-(char*)&amp;v[0])); } </code></pre> <p>The message is <code>error: alignment of array elements is greater than element size</code>. </p>
    singulars
    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.
    3. VO
      singulars
      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