What does it mean to "dynamically create" something? |
For example, let's say you need to create an array but you don't the size until run time due to it being dependent on some form of input. Well the compiler needs to know at compile the size of the array. The way around this is to use dynamic allocation. When this is done, memory is given to the program from the
heap which is different than static memory which lies on the
stack. These are terms you should get familiar with.
Pointers in and of themselves are very simple. All a pointer is is a data type which holds an address of some place in memory, ie a variable. So instead of dragging the whole variable around you can just store it's address and access indirectly that way.
Think of pointers as a phone number of a friend. When you want to get in touch with your friend quickly, do you get in your car and drive all the way to his house? Or do you just call him? His phone number would be the pointer in this situation, and calling him and retrieving the information would be
dereferencing the pointer. In this analogy, driving to his house and talking to him would similar to manipulating variables directly,
by value.
Now I made this analogy up on the spot so don't hate if it's not perfect.
Here's how they work in practice.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
int* ptr; //This is a variable called ptr that is of type int*. This means it points to an int.
int* ptr2 = new int[runTimeVar]; //The new keyword is how you dynamically create something. This allows variable length arrays.
char* ptr3; //ptr3 points to a char.
int* ptr;
double val;
ptr = val; //Invalid. Can't assign non pointer types to a pointer. Only pointer to pointer.
ptr = &val; //Also invalid. We already declared ptr as pointing to an int, not a double.
int num;
ptr = # //This is valid. This now makes ptr point at num. ptr now stores num's address.
int* ptr2;
ptr = ptr2; //This is valid. This makes ptr point to the same ptr2 is pointing at. Their values are now the same,
//ie they hold the same memory address. This does not mean they are sitting in the same memory address though.
|