Game Development Reference
In-Depth Information
Listing 4-4. Using a Pointer with an Array
int _tmain(int argc, _TCHAR* argv[])
{
int intArray[5] = { 0, 1, 2, 3, 4 };
cout << "Value: " << *intArray << endl;
cout << "Value: " << *(intArray + 1) << endl;
cout << "Value: " << *(intArray + 2) << endl;
cout << "Value: " << *(intArray + 3) << endl;
cout << "Value: " << *(intArray + 4) << endl;
return 0;
}
Listing 4-4 creates a program that outputs the values stored in the array. However, it accesses the
values in the array by manipulating a pointer as opposed to using the index operator. Once again we
have used parentheses in our program to dictate the order in which our operators are evaluated.
As you can see, the array is created as usual; however, this time it is clear that the variable intArray
is actually a pointer to an int . We can manipulate the array variable using pointer arithmetic to
achieve the same result as using the index operator. The first value is accessed by dereferencing the
pointer, and each subsequent value is accessed by dereferencing the pointer after it has been offset
using pointer arithmetic.
Now that you know how to access arrays using either the index operator or pointers, we are ready to
tackle C style strings.
C Style Strings in Arrays
Listing 1-1 showed the use of a C++ style string using the string class. We look at this class in
detail in Chapter 13 once we have covered classes in more detail. Until then we can use arrays to
represent C style strings.
Note It is recommended that STL strings are used in new programs. STL strings automatically resize to
store strings of varying length and generally hide all of the complicated memory management processing that
can be involved when working with C style strings. This chapter covers C style strings, as you are likely to
come across these very often when dealing with older game code and legacy game engines or libraries.
Listing 4-5 shows how we can access a C style string via pointer.
Listing 4-5. A C Style String
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
 
 
Search WWH ::




Custom Search