Skip to content

Instantly share code, notes, and snippets.

@JohannesMP
Created July 15, 2012 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohannesMP/6b3b2933996214d1ff42 to your computer and use it in GitHub Desktop.
Save JohannesMP/6b3b2933996214d1ff42 to your computer and use it in GitHub Desktop.
resize_array.cpp example file fixed
#include <iostream>
using namespace std;
int *growArray (int* p_values, int* p_cur_size);
int main ()
{
int next_element = 0;
int size = 2;
int *p_values = new int[ size ];
int val;
cout << "Please enter a number for element " << next_element << " of " << size - 1 << ": ";
cin >> val;
while ( val > 0 )
{
if ( size == next_element + 1 )
{
p_values = growArray( p_values, &size );
}
p_values[ next_element ] = val;
next_element++;
cout << "Please enter a number for element " << next_element << " of " << size - 1 << " (or 0 to exit): ";
cin >> val;
}
}
int *growArray (int* p_values, int *p_cur_size)
{
cout << "\n - Array resized! was " << *p_cur_size << " long, ";
int *p_new_values = new int[ *p_cur_size * 2 ];
*p_cur_size *= 2;
cout << "is now " << *p_cur_size << " long. \n\n";
for ( int i = 0; i < *p_cur_size; ++i )
{
p_new_values[ i ] = p_values[ i ];
}
delete p_values;
return p_new_values;
}
@alexi21
Copy link

alexi21 commented Feb 14, 2016

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment