Game Development Reference
In-Depth Information
We use an unsigned int as the array index, as we will never require a negative index into our array.
Our index is initialized to 0 to access the first element and we use the post increment operator to
increase the index by one after we print each value from the array.
Note You must make sure to initialize the array index to 0 in Listing 4-2 to ensure that we access the first
element of the array. If you had failed to initialize the index in production code, the variable could contain a
random value and access memory outside of the array. This always leads to bugs that are hard to locate and
fix. The same principle of always initializing should apply to all of your variables to avoid this problem.
Listing 4-2 has also changed the values in the array to prevent the same values from being printed
out for both the index and value lines. This helps show the relationship between the index and the
values contained within the array.
Arrays can be constructed using any type in C++. Listings 4-1 and 4-2 show arrays using the int
type but we could just as easily have used float , short , or bool (for example). char arrays have
special meaning in C++ under certain circumstances as they can be used to represent C style
strings.
Before we can look at the functions that C++ provides to manipulate C strings, you need to
understand how pointers work and their relationship with arrays and memory.
Pointers
Pointers are a fundamental aspect of the C++ language that allows it to deliver fast runtime
performance as a low-level programming language. Where variables allow us to manipulate the
values stored at specific locations in memory, pointers let us manipulate variables that store
addresses to other variables.
The concept of pointers can be a difficult one to explain, so let's jump straight into some examples.
Listing 4-3 shows how we can use a pointer to find the value stored at a given memory address.
Listing 4-3. Using Pointers in C++
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int variable = 5;
int* variablePointer = &variable;
cout << "Value of variable: " << variable << endl;
cout << "Address of variable: " << &variable << endl;
 
Search WWH ::




Custom Search