In C++, there are two ways to allocate memory - statically and dynamically. For statically allocated variables, you need to know at compile time exactly how much memory is needed. Here are some examples:
int i; float float_arr[100]; char filename[100]; vector <int> v; // note: the vector is statically allocated, while its // contents may not be! string s; // again, s is static, but the string class will // dynamically allocate space to store the data graph g; // assuming that a graph is a user-defined classIf you do not know at compile time how much space is needed, then you need dynamically allocated memory. Since the size is unknown until the program runs, the program must decide during execution exactly where in the program's memory segment to allocate space. You must use a pointer variable to store this memory location. So, to dynamically allocate memory, do the following
new
to allocate memory to store the data
*
delete
to
release (recycle) the memory
int *ip; // ip is a pointer variable
ip = new int; // dynamically allocate space for the int
// and make ip point to it
cin >> *ip; // store a number in the memory that's been allocated
cout << "You typed the number " << *ip << endl;
cout << "We are storing this number in the memory location " << ip << endl;
delete ip;
ip = 0;
// This is a stupid example - if you only need one int
, then
// it makes more sense to just just create an int variable
Here's another example, using arrays:
int i, arrsize(0); int *arr; // arr is a pointer - it will point to an array of ints cout << "How big is the array? "; cin >> arrsize; // this number better be nonnegative - in a real program, // you should check the user's input arr = new int[arrsize]; cout << "Enter " << arrsize << " integers: "; for (i=0; i < arrsize; i++) cin >> arr[i]; cout << "Here are the numbers you entered: " for (i = 0; i < arrsize; i++) cout << arr[i] << " "; delete [ ] arr; arr = 0;Here's another way to do the last few lines of the previous example. It shows a couple of ways to handle pointers:
int *p=arr; for (i=0; i < arrsize; i++, p++) cin >> *p; cout << "Here are the numbers you entered: " for (i = 0; i < arrsize; i++) cout << *(arr+i) << " "; delete [ ] arr; arr = 0;Remember that any time you allocate memory with
new
, you should
release it with delete
. Never use delete
with
statically allocated memory. For example:
int i; int *ip = &i; cin >> *ip; delete ip; // This is an error! ip points to the variable i, // which is statically allocated memory.