Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are two types of arrays you should be able to distinguish. One looks like this:</p> <pre><code>type name[count]; </code></pre> <p>This array is of type <code>type[count]</code> which is a different type for each <code>count</code>. Although it is convertable to <code>type *</code>, it is different. One difference is that <code>sizeof(name)</code> gives you <code>count*sizeof(type)</code></p> <p>The other type of array looks like this:</p> <pre><code>type *name; </code></pre> <p>Which is basically just a pointer that you <em>could</em> initialize with an array for example with <code>malloc</code> or <code>new</code>. The type of this variable is <code>type *</code> and as you can see, there are no <em>count</em> informations in the type. Therefore, <code>sizeof(name)</code> gives you the size of a pointer in your computer, for example 4 or 8 bytes.</p> <p>Why are these two <code>sizeof</code>s different, you ask? Because <code>sizeof</code> is evaluated at compile time. Consider the following code:</p> <pre><code>int n; cin &gt;&gt; n; type *name = new type[n]; </code></pre> <p>Now, when you say <code>sizeof(name)</code>, the compiler can't know the possible future value of <code>n</code>. Therefore, it can't compute <code>sizeof(name)</code> as the real size of the array. Besides, the <code>name</code> pointer might not even point to an array!</p> <p>What should you do, you ask? Simple. Keep the size of the array in a variable and drag it around where ever you take the array. So in your case it would be like this:</p> <pre><code>void assignArray(int *myArray, int size) { for(int k = 0; k &lt; size; ++k) { myArray[k] = k; } } </code></pre>
 

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