Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Putting aside the problems with your code, yes, arrays are contiguous elements.</p> <p>What happens with the second line of the code snippet below:</p> <pre><code>int * iptr = malloc (40 * sizeof(int)); int x = iptr[10]; </code></pre> <p>is thus:</p> <ul> <li>the value <code>10</code> is multiplied by the size of the <code>int</code> to get 70 (in this example, we assume a 7-byte <code>int</code>).</li> <li>this is then added to the base pointer <code>iptr</code> (unscaled) and the (7-byte) value is extracted from that location.</li> </ul> <p>This scaling is an important feature. You won't see it when you're working with <code>char</code> arrays but the values <code>&amp;(iptr[0])</code> and <code>&amp;(iptr[1])</code> will be separated by the size of an <code>int</code>, <em>not</em> a <code>char</code> (7 in our example case above).</p> <p>When you add 1 to a pointer, that doesn't actually add 1, it adds the size of the underlying data type. So that:</p> <pre><code>int *p = &amp;(iptr[0]); p++; </code></pre> <p>won't give you an address corresponding to the second <em>byte</em> of that memory, it will actually give you the address of the second <code>int</code> (the seventh byte).</p> <p>To that end, <code>iptr[3]</code> is exactly equivalent to <code>*(i+3)</code> in that they both give you element number three, even though it's made up of <em>bytes</em> from offset 21 through 27 inclusive.</p> <hr> <p>Pre-emptive strike, just in case: keep in mind that a byte in ISO C is <em>not</em> necessarily 8 bits. ISO uses the term <code>octet</code> for that. A <em>byte</em> is the size of a <code>char</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