How annoying.
So, back on topic: Pointers! To demonstrate the power of pointers, I'm going to talk about using them to make arrays and handle memory.
A plain "array" is a structured collection of entities. For example: a list is an array intended for an objective, usually used in a sequence (e.g. a check list or shopping list).
A dynamic array is much more complicated however; because, they are designed to be resized and changed often.
Now, imagine a game with a slow & steady flow of enemies coming into the level, while you're fending off these enemies and eliminating them one by one. As a programmer, how would you manage this? Well, you may have heard of the Standard Template Library's class called "vector". It's just a dynamic array.
C++ has some nice features which are very helpful for implementing a dynamic array yourself. It has built-in operators designed for allocating new memory, as well as freeing it. Look at this:
1 2
|
// Create an array of 5 integers:
int* integerArray = new int[5];
|
The "new" operator will allocate (find available/reservable) memory for int[5]; which is five integers.
Logically, I start with "int" for the type. Then there's an asterisk (*) which makes it a pointer to one or more integers. Now it is possible to point to the memory location which was just allocated for five integers.
So, I can start putting integers into the array:
1 2 3 4 5
|
integerArray[0] = -1;
integerArray[1] = 6;
integerArray[2] = 13;
integerArray[3] = 5;
integerArray[4] = -7;
|
There, that's five integers! Notice: I start at zero and end with four, rather than starting at one and ending with five. That's because, the number (index) which I put between the '[' and ']' merely means an offset in memory.
That kind of translates to:
integerArray+index*sizeof(int)
Do you get the idea a little better now?
Well I'm going to bed. Checkout:
http://www.cprogramming.com/tutorial/c/lesson6.html
http://cplusplus.com/doc/tutorial/pointers/