Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't because there's no automatic cast that can be used.</p> <p>Remember that you can't pass an array to a function by value: an array parameter is really just a pointer parameter, so the following two are the same:</p> <pre><code>void f(long a[]); void f(long* a); </code></pre> <p>When you pass an array to a function, the array is implicitly converted to a pointer to its initial element. So, given <code>long data[10];</code>, the following two are the same:</p> <pre><code>f(data); f(&amp;data[0]); </code></pre> <p>There is no implicit conversion from <code>short*</code> to <code>long*</code>, so if <code>data</code> were declared as <code>short data[10];</code>, you would get a compilation error. </p> <p>You would need to explicitly cast the <code>short*</code> to a <code>long*</code>, using <code>reinterpret_cast</code>, but that won't convert "an array of N <code>short</code> elements" into "an array of N <code>long</code> elements," it will reinterpret the pointed-to data as "an array of [some number of] <code>long</code> elements," which probably isn't what you want.</p> <p>You need to create a new array of <code>long</code> elements and copy the elements from the array of <code>short</code> into the array of <code>long</code>:</p> <pre><code>short data[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; long data_as_long[10]; std::copy(data, data + 10, data_as_long); f(data_as_long); </code></pre> <p>Or, you might consider changing your function to be a template that can accept a pointer to an array of any type of element:</p> <pre><code>template &lt;typename T&gt; void f(T*); </code></pre> <p>Or, for a more advanced solution, the most generic way to do this would be to have your function take an iterator range. This way, you could pass it any type of iterator (including pointers into an array). In addition, it provides a natural and simple way to ensure that the length of the array is passed correctly, since the length is not passed explicitly, it's determined by the arguments.</p> <pre><code>template &lt;typename Iterator&gt; void f(Iterator first, Iterator last); const unsigned length_of_data = 10; long data_array[length_of_data]; std::vector&lt;long&gt; data_vector(length_of_data); f(data_array, data_array + length_of_data); // works! f(data_vector.begin(), data_vector.end()); // also works! </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