Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm not going to bother with a line-by-line code analysis since (a) you're changing it while people are answering your question and (b) it would literally take too long. But here's a summary (non-exhaustive) of klunkers:</p> <ol> <li>You are leaking memory (newArr) on each loop iteration starting with the second. </li> <li>You're out-of-bounds on your array access multiple times.</li> <li>You should not <em>need</em> to use a pointer array <em>at all</em> to solve this. A single array of dimension [N][2] where N is the number of unique values.</li> </ol> <p>One (of countless many) way you can solve this problem is presented below:</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; int main() { // 0. Declare array and length int arr[]={6,7,3,1,3,2,4,4,7,5,1,1,5,6,6,4,5}; const size_t NR = sizeof(arr)/sizeof(arr[0]); // 1. sort the input array std::sort(arr, arr+NR); /* alternaive sort. for this input size bubble-sort is more than adequate, in case your limited to not being allowed to use the standard library sort */ /* for (size_t i=0;i&lt;NR;++i) for (size_t j=i+1;j&lt;NR;++j) if (arr[i] &gt; arr[j]) { arr[i] ^= arr[j]; arr[j] ^= arr[i]; arr[i] ^= arr[j]; } */ // 2. single scan to determine distinct values size_t unique = 1; for (size_t i=1;i&lt;NR;++i) if (arr[i] != arr[i-1]) unique++; // 3. Allocate a [unique][2] array int (*newArr)[2] = new int[unique][2]; // 4. Walk array once more, accumulating counts size_t j=0; newArr[j][0] = arr[0]; newArr[j][1] = 1; for (size_t i=1;i&lt;NR;++i) { if (arr[i] != arr[i-1]) { newArr[++j][0] = arr[i]; newArr[j][1] = 0; } ++newArr[j][1]; } // 5. Dump output for (size_t i=0;i&lt;unique;++i) cout &lt;&lt; newArr[i][0] &lt;&lt; " : " &lt;&lt; newArr[i][1] &lt;&lt; endl; delete [] newArr; return EXIT_SUCCESS; } </code></pre> <p><strong>Output</strong></p> <pre><code>1 : 3 2 : 1 3 : 2 4 : 3 5 : 3 6 : 3 7 : 2 </code></pre>
    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. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    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