title: Is there a way of casting a pointer to an array type?
body: <p>C arrays are somewhat difficult to understand syntactically in C++ and can take some getting used to.  Although a 1D array decays to a pointer:</p>
  
  <pre><code>void fn1(int x[2]) {}
  void fn2(int*x) {}
  </code></pre>
  
  <p><code>fn1()</code> and <code>fn2()</code> have the same function signature.</p>
  
  <p>An array actually does have a type that includes how many elements are in the array.  As in:</p>
  
  <pre><code>void fn(int (&amp;)[2]) {}
  </code></pre>
  
  <p><code>fn()</code> will only accept a 2 element int array.</p>
  
  <p>Thing is, I can only see that the array of a fixed number of elements can only be generated by stack, file scope or struct/class allocation with that signature:</p>
  
  <pre><code>int twoElementArray[2];
  </code></pre>
  
  <p>If I were to dynamically allocate it on the heap, I can't seem to get the same signature.  I thought that I might be able to cast it, but without success:</p>
  
  <pre><code>int (&amp;array)[2] = reinterpret_cast&lt;int(&amp;)[2]&gt;(new int[2]); // FAIL!
  </code></pre>
  
  <p>Any ideas as to how this might be accomplished if at all?</p>
  
  <p>&nbsp;</p>
  
  <hr>
  
  <p><strong>EDIT:</strong> Although I selected an answer, it actually doesn't actually cast anything, but uses a definitely better method then casting (better not to cast if not required IMO).  However, it technically doesn't answer the question since the question asked if there's "a way of casting a pointer to an array type?"  The answer is yes.</p>
  
  <pre><code>int (&amp;array)[2] = *reinterpret_cast&lt;int(*)[2]&gt;(new int[2]); // SUCCESS!
  </code></pre>
  
  <p>Note that I don't necessarily recommend doing this, but it does answer the question.  If I needed to convert a pointer to an array type though, that would be how to do it.  Read the picked answer for a better solution when using <code>operator new[]</code>.</p>