I didn't know what the point of pointers was until yesterday upon reading Prata. I learned that you use pointers to allocate memory with the new operator. I guess there is no other way. Before I found about runtime decisions vs. compile time decisions I thought that there was no point to pointers and you could always just pass by reference. What about runtime decisions vs compile time decisions? well, a runtime decision is a decision that is made while the program is running and a compile time decision is a decision made while the program is being compiled. When you're making a very large program you want to manage memory so that variables or arrays aren't all loaded into memory if they don't need to be loaded into memory. There's a lot of talk about heap or stack. I can't remember where memory allocated by new goes. Any who, maybe you don't want memory space to be allocated until certain conditions are met.
if (GetAnswer() == true;)
{
int * p_number = new int; // allocated memory with new
cout << "You get " << *p_number << " points!"; //dereferencing the pointer to display value and not address } However, you usually don't want to use pointers for programs with just a few variables. Another cool thing about pointers and allocating with the new is dynamic binding. Static binding is when you create an array with a fixed amount of elements, but when you dynamically bind you allocate an array and you make the size of the array a variable. e.g.
Code:
#include <iostream>
using namespace std;
int main()
{
int ArraySize;
cin>> ArraySize;
int * p_numbers = new int [ArraySize];
for (int x = 0; x <= ArraySize; x++){ p_numbers[x] = x; cout<<<>>f;
return 0;
}
You wouldn't be able to complete the same task with normal arrays.
No comments:
Post a Comment