Arrays Are Pointers in Disguise


There is a strong connection between arrays and pointers. In fact, arrays are pointers. I like to say that they're pointers in disguise because they don't look like pointers. Unlike pointers, arrays must always point to the same block of memory. Also, the size of that memory block never changes. It's statically allocated.

Because pointers and arrays are related, it's possible to allocate a block of memory with a pointer and then treat it like it's an array. That's very convenient.

In addition, the close relation of pointers and arrays means that it is possible to create dynamically allocated arrays that change size. This is a somewhat advanced technique that I won't demonstrate in this book. However, I do want you to be aware that the possibility exists. For now, I'll just present a program in Listing 11.5 that shows how to allocate a block of memory and treat it as an array.

Listing 11.5. The equivalence of pointers and arrays

 1     #include <cstdlib> 2     #include <iostream> 3 4     using namespace std; 5 6     int main(int argc, char *argv[]) 7     { 8         int *someInts = new int [10]; 9         if (someInts==NULL) 10        { 11            return (-1); 12        } 13 14        int i=0; 15        while (i<10) 16        { 17            someInts[i] = 10-i; 18            i++; 19        } 20 21        i=0; 22        while (i<10) 23       { 24            cout << someInts[i] << endl; 25            i++; 26       } 27 28       delete [] someInts; 29 30       system("PAUSE"); 31       return EXIT_SUCCESS; 32    } 

The short program declares a variable that is a pointer to integers on line 8 of Listing 11.5. It also allocates memory for 10 integers. On lines 1419, the program uses a loop to store integers into the block of memory it allocated. Notice in particular line 17. Even though someInts is declared as a pointer to integers rather than an array, the program can still use array notation with the pointer. It is perfectly acceptable to use array notation with the variable someInts because there's a fundamental equivalence between pointers and arrays.

Most programmers find it much easier to deal with array notation rather than pointer notation. The loop on lines 2126 iterates through the block of memory and prints the integers the memory contains. Once again, it uses array notation with the pointer variable someInts. C++ compilers have no problem with this.

It is very common for C++ programmers to use array notation with pointers in all types of programs. This technique is not limited to games.



Creating Games in C++(c) A Step-by-Step Guide
Creating Games in C++: A Step-by-Step Guide
ISBN: 0735714347
EAN: 2147483647
Year: N/A
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net