-
-
Save JohannesMP/6b3b2933996214d1ff42 to your computer and use it in GitHub Desktop.
resize_array.cpp example file fixed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!