Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all, never do this in real-world code. You will blow off your leg, look like an idiot and all the cool kids will laugh at you.</p> <p>That being said, here's how it works: The basic idea is that the size of an int is equal to the offset between two elements in an int array in bytes. Ints in an array are tightly packed, so the beginning of the second int comes right after the end of the first one:</p> <pre><code>int* intPtr1 = &amp;intArray[0]; int* intPtr2 = &amp;intArray[1]; </code></pre> <p>The problem here is that when subtracting two int pointers, you won't get the difference in bytes, but the difference in ints. So <code>intPtr2 - intPtr1</code> is <code>1</code>, because they are 1 int apart.</p> <p>But we are in C++, so we can cast pointers to anything! So instead of using int pointers, we copy the value to char pointers, which are 1 byte in size (at least on most platforms).</p> <pre><code>char* charPtr1 = reinterpret_cast&lt;char*&gt;(intPtr1); char* charPtr2 = reinterpret_cast&lt;char*&gt;(intPtr2); </code></pre> <p>The difference <code>charPtr2 - charPtr1</code> is the size in bytes. The pointers still point to the same location as before (i.e. the start of the second and first int in the array), but the difference will now be calculated in sizes of <code>char</code>, not in sizes of <code>int</code>.</p> <p>Since the exercise did not allow <code>reinterpret_cast</code> you will have to resort to another trick. You cannot <code>static_cast</code> from <code>int*</code> to <code>char*</code> directly. This is C++'s way of protecting you from doing something stupid. The trick is to cast to <code>void*</code> first. You can <code>static_cast</code> any pointer type to <code>void*</code> and from <code>void*</code> to any pointer type.</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. 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