Please send questions to
st10@humboldt.edu .
/*-----
Signature: main: void -> int
Purpose: to demonstrate a dynamically-allocated array
Examples: When called, if when prompted the user enters
3
and then
15
20
13
then the following will be printed to the screen:
15
20
13
by: Sharon Tuttle
last modified: 12-3-10
-----*/
#include <iostream>
using namespace std;
int main()
{
// local variables
int *quant_array_ptr; // LOOKS like a pointer to an int --
// BUT we'll set up to point to
// an int ARRAY, instead;
int num_quants;
// how big shall the quantity array be?
cout << "how many quantities are there? ";
cin >> num_quants;
// now I want to dynamically allocate an array of ints
// of that size
quant_array_ptr = new int[num_quants];
// and now, I can STILL use the array notation I'm used to!
// ...for example, to interactively fill the array;
for (int i=0; i<num_quants; i++)
{
cout << "what is the next quantity? ";
cin >> quant_array_ptr[i];
}
// COULD do other stuff here, if desired;
// prove it has been filled/see what's in the array now
for (int i=0; i < num_quants; i++)
{
cout << quant_array_ptr[i] << endl;
}
// but BE CAREFUL!!! to FREE the dynamically-allocated
// array, you need to use SPECIAL SYNTAX!!!!!
// (compiler needs a clue to deallocate a whole array,
// not just a single value...)
delete [ ] quant_array_ptr;
quant_array_ptr = NULL; // good style: set to NULL
// after you deallocate what
// it points to...!
// (although not QUITE as vital if
// the delete is the LAST line of
// the function...)
return EXIT_SUCCESS;
}