title: How to get size of dynamic array in C++
body: <p>Code for dynamic array by entering size and storing it into "n" variable, but I want to get the array length from a template method and not using "n".</p>
  
  <pre><code>int* a = NULL;   // Pointer to int, initialize to nothing.
  int n;           // Size needed for array
  cin &gt;&gt; n;        // Read in the size
  a = new int[n];  // Allocate n ints and save ptr in a.
  for (int i=0; i&lt;n; i++) {
      a[i] = 0;    // Initialize all elements to zero.
  }
  . . .  // Use a as a normal array
  delete [] a;  // When done, free memory pointed to by a.
  a = NULL;     // Clear a to prevent using invalid memory reference.
  </code></pre>
  
  <p>This code is similar, but using a dynamic array:</p>
  
  <pre><code>#include &lt;cstddef&gt;
  #include &lt;iostream&gt;
  template&lt; typename T, std::size_t N &gt; inline
  std::size_t size( T(&amp;)[N] ) { return N ; }
  int main()
  {
       int a[] = { 0, 1, 2, 3, 4, 5, 6 };
       const void* b[] = { a, a+1, a+2, a+3 };
       std::cout &lt;&lt; size(a) &lt;&lt; '\t' &lt;&lt; size(b) &lt;&lt; '\n' ;
  }
  </code></pre>