Note that there are some explanatory texts on larger screens.

plurals
  1. POBetter way to use a pointer?
    text
    copied!<p>I'm trying to create a program that will display bar graphs with * the maximum number of * can be 40. I have everything working but had a question with the code. Is there a better way as you can see I have to go back to the original address twice using:</p> <pre><code> p_bar_length = p_bar_length - size; </code></pre> <p>Is there a better way to do this?</p> <pre><code>#include &lt;iostream&gt; using namespace std; const int MAX_SPLATS = 40; void bar_chart(double values[], int size) { double largest = values[0]; //assign first element to be the largest //Find the largest value for (int i = 1; i &lt; size; i++) { if (largest &lt; values[i]) // check to see if there is something larger { largest = values[i]; } } // Find the number of spalts to use // with the precent based on the largest value int* p_bar_length = new (nothrow) int[size]; for (int i = 0; i &lt; size; i++) { *p_bar_length = (values[i] / largest) * MAX_SPLATS; p_bar_length++; // Go to next memory address } // Go back to the orignal memory address p_bar_length = p_bar_length - size; // Pritnt the correct number of splats for (int i = 0; i &lt; size; i++) { for (int j = 0; j &lt; *p_bar_length; j++) { cout &lt;&lt; "*"; } p_bar_length++; cout &lt;&lt; endl; } // Go back to the orignal memory address p_bar_length = p_bar_length - size; delete[] p_bar_length; } int main() { double values[6] = { 22, 40, 28, 26, 14, 46}; int val_size = 6; bar_chart(values, val_size); system("pause"); return 0; } </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