Home | Gaming | Programming | Play Online | Contact | Keyword Query
Games++ Games & Game Programming

Games++ Home
Games++ Gaming
Games++ Programming
Beta Testing Games
Free Online Games
Hints & Cheats

E-mail This Page
Add to Favorites


Web Games++

Cheat Codes
Trickster Wiki
Game Ratings
Gameboy Cheats
PlayStation Cheats
BlackBerry Games
Photoshop Tutorials
Illustrator Tutorials
ImageReady Tutorials



Ch 5: Handling More Complex Data - C++ by Metrowerks

Introduction to C++ by Metrowerks

One-Dimensional Arrays and Basic String Library Functions

It is often necessary to create a set of several related variables. An array is a collection of variables of the same type that is called by a single name. Arrays can be one-dimensional or multi-dimensional. We will discuss one-dimensional arrays in this section.

One-Dimensional Arrays

A one-dimensional array is a list of related variables. A one-dimensional array declaration looks like this:

type onedarrayname[size];

All elements in the above array will be of a single type. The size of the array is the number of elements contained in that array. Therefore, to create a one-dimensional array named list1 with 15 elements of type int, the declaration would be:

int list1 [15];

To access individual elements within the array, simply reference the index number of the desired element. The index of elements always begins with 0. Therefore, in our above array, the elements are indexed 0 through 14. The first element is list1[0] and the last element is list1[14]. Following is a sample program that loads the numbers 0-14 into the above array:

using namespace std;
int main()
    int list1[15];
    int e;
    for (e=0; e<15; ++e) list1[e]=e;>
    return 0;

An array can also be loaded with random numbers:

using namespace std;
int main()
    int list2[10];
    int r;
    for (r=0; r<10; r++) list2[r] = rand ();>
    return 0;

C++ will not verify the actual number of elements in your array. If you declare an array of 10 elements and try to fill that array with 15 elements, your system may crash. The additional five elements will overwrite whatever data or additional code is contained in the next section of memory.

Strings and String Library Functions

A string is an array of characters that terminates with a zero represented by the escape sequence \0. Since all strings terminate in this way, to avoid confusing your compiler you must declare each char array to be one element larger than the size of the string you want that array to hold. As we discussed earlier in the course, a string constant is a list of characters enclosed in double quotes. We'll talk more about them later.

Reading a String from the Keyboard

There is one major problem with using a cin >> statement to read a string directly from the keyboard. When the program comes to the first blank space (space, tab, newline, etc.) in the string, it will think that end of the string is the end of the program. Therefore, inputting a string such as

"This is a string."

using the cin statement will result in a string consisting only of


To circumvent this problem, the cin.get(char *, int size) and cin.getline(char *, int size) command should be used. The get() command is a member of the C++ iostream library of functions. The following sample program will read and output a string from the keyboard using the get() function:

using namespace std;
int main()
    const int arraySize = 51;
    char string1[arraySize];
    cout << "Input no more than 50 characters: ";
    cin.get(string1, arraySize);
    cout << string1;
    return 0;

Using C++ streams gives some safety but still does not verify the number of elements in an array. Even though the request for input specifies 50 characters, nothing is stopping the operator from inputting more than 50 characters. If this program is run with more than 50 characters in the array, only 50 characters will be stored in the array. If you have an array smaller than specified for input, the system may crash. If you input more than the number specified, the remainder will stay in the buffer and a fail bit may be set on input.

String Library Functions

All of the string library functions that we are about to discuss are contained within the header file .

The first function we will consider is strcpy(). As you can probably guess, this function copies the contents of one string into another. To copy the contents of string source into string dest, type:

strcpy(dest, source);

The string function strcmp() compares two strings. If the strings are equal, the return value is 0. If s1 is greater than s2, a positive number is returned. If s2 is greater than s1, a negative number is returned.

The key to using this function is to remember that a value of 0 or false (remember Boolean constants?) is returned whenever the data in the two strings match. It's tricky, but you'll get used to it as you use these functions. The following sample program requests a password. If the entered password matches the password specified in the program, then access is granted. If not, access is denied.

using namespace std;
bool password();
int main()
    if (password()) cout << "Access granted.";
    else cout << "Access denied.";
    return 0;
bool password()
    char s1[50];
    cout << "Please enter the password: ";
    if (strcmp(s1, "programming")) return false;
    return true;

The final string function we will mention is the strlen() function. As its name implies, it returns a value equal to the length of the string.

Calling Functions With Arrays

When a function is called with an array, the whole array is never passed as the argument for that array; a pointer to the first element in the array is instead passed. A specific element of an array can also be passed. Therefore, the simplest and most widely used method of passing an array to a function is by using a pointer. Look at the following program and see how it uses a pointer to pass an array to a function:

using namespace std;
void f1(int *p);
int main()
    int a[10],i;
    for(i=0; i<10; ++i) a[i]=i; // loads values into the array     f1(a); // passes the array>
    return 0;
void f1(int *p)
    int j;
    for(j=0; j<10; j++) cout ><< p[j] << ' ';

The name of an array is an alias to a pointer to the first element of an array. This is a shortcut developed for programmers, since it is so common to pass an array as a pointer.

You can pass an array as an array argument, but you have to list the array sizes of all but the last dimension. You cannot return an array from a function -- you must return a pointer to the array. Generally the object of passing an array is so it may be modified. Therefore, in almost every case, an array is passed by address using a pointer to the array.

Multi-Dimensional Arrays

C++ allows the programmer to create multi-dimensional arrays. Multi-dimensional arrays are essentially complicated table structures -- a two-dimensional array is like a spreadsheet. A three-dimensional array is like a cube of data. It's unlikely that you will ever need to create an array with more than three dimensions. After our initial study of multi-dimensional arrays, we will look at array initialization and arrays composed of strings.

Two-Dimensional Arrays

The declaration of a two-dimensional array of integers, named array2, with dimensions of 5 by 10 would look like this:

int array2[5][10];

The left index indicates the number of rows vertically and the right index indicates the number of columns horizontally. To successfully picture a two-dimensional array, think of a multiplication table. You have a vertical set of numbers on the left side (in the case of the above array, the numbers 0-4) and a horizontal set of numbers across the top (0-9). To access an individual cell, reference the left number and the top number. Bring the left number in, bring the top number down, and find the location of the cell where the two values meet. For example, to output point 2,3 in the above array to the screen, type this:

cout << array2[2][3];

Arrays of Three or More Dimensions

Arrays of more than two dimensions are not commonly used in C++. The main problem is that large, multi-dimensional arrays require a lot of memory. To declare a three-dimensional array, however, of integers of size 5, 10, 20, you would use the following form:

int array3[5][10][20];

For each subsequent dimension, simply add the dimension size in brackets.

Array Initialization

An array can be initialized much like the other variables we have studied. The following are examples of one-dimensional array initializations:

int intarray[5] = {1, 2, 3, 4, 5};
char strarray[8] = "testing";
char strarray2[8] = {'t', 'e', 's', 't', 'i', 'n', 'g', '\0'};

When defining multi-dimensional arrays, it is sometimes easier to think of the structure as a series of rows and columns. However, it is important to remember that the rows are filled in contiguous memory -- there are not really any rows or columns, just a series of values in memory. This is important to remember when using pointers, as you will see in the next section.

Following are two ways to initialize a two-dimensional array:

int twoarray[2][5] = {


int twoarray[2][5] = {

Note: This second method is only used for specific types and should be avoided so as not to create a bad habit in C++.

An array initialized outside of all functions in a program is called a global array. Global arrays are available to all functions within a program. A global array can also be initialized within an individual function. In this case, the array is re-initialized each time the function is repeated.

An array can be successfully initialized without a specific dimension when it is created. This is called an unsized array. In this case, C++ will automatically create an array of the correct size to hold the data:

char uarray[] = "This is an unsized array\n";

Using an unsized array has two major advantages. First, the programmer does not need to specifically enumerate the elements in an array or worry about declaring an array of inadequate size. Secondly, changing the elements of an array does not change the declaration of that array. Therefore, it's easy to go back to your code and make changes without having to recount the elements.

It also has several disadvantages. You may share the intialization value with a different unsized array. If you were to then modify one, you may modify another. This array can't hold more characters than the original allocation, meaning you can't add to it at some later point. It is best in most uses to declare unsigned arrays as const, to ensure you do not modify them.

Arrays of Strings

One common way to use two-dimensional arrays is to create an array of strings. The left index determines the number of strings in the array, and the right index determines the maximum length of each string.

Next Lesson

Copyright © 1998-2007, Games++ All rights reserved. | Privacy Policy