Edited the post ^^
Making this a good useful post:
Think of a simple...
int C = 0;
"A pointer to C" means the RAM address of the "C" variable.
If you go look deeply into your ram, at the position of "A pointer to C", you will see the C value. (Just as an example).
The type itself of a pointer is:
int * pC = &C;
Examinate the first half of the above statement.
Now, pC is "A pointer to C".
The value of pC will be the RAM position of C.
&C means the actual position in the RAM of the variable C.
Say we want to take the RAM address of variable D, you would write &D instead.
To access that RAM location, you only need to add a * prefix:
*pC = 42;
At this point, also C will be 42, because you changed its content in the ram, using the pointer.
Now, the deal with pointers is no stack overflows and dynamic size of allocation, things that aren't possible without using pointers, so, yes, it's important.
Say you want an array of a size you don't know:
int * P = new int[ MySize ];
Knowing the first part:
The second part (
new int //...
) simply means:
Give me an address in the RAM that is not being used and that is big enough.
Reserve its usage to me.
Now this should have done it quite clear.
But one thing happens:
How does your OS know when you're done using your RAM?
Simple: You have to tell him (Something you forgot to do, above).
1 2 3 4
|
int * P = new int[ MySize ];
// Use *P freely
delete[] P; // This tells your OS to stop reserving this block of memory to you
P = 0; // But you must make sure not to use it anymore.
|
Now notice a little difference:
For arrays you do:
1 2 3 4
|
int * P = new int[ MySize ];
// ...
delete[] P;
P = 0;
|
But for single objects:
1 2 3 4
|
int * P = new int;
// ...
delete P; // Don't use [] in delete, if you didn't use [...] in new.
P = 0;
|
Anymore questions or still need help on the topic, post a reply.