How to Create an Array of Characters in C++

By Stephen R. Davis

The elements of an array in C++ can be of any type. Arrays of floats, doubles, and longs are all possible; however, arrays of characters have particular significance.

Human words and sentences can be expressed as an array of characters. An array of characters containing the name Stephen would appear as

char sMyName[] = {'S', 't', 'e', 'p', 'h', 'e', 'n'};

The following small program displays this name:

// CharDisplay - output a character array to
//               standard output, the MS-DOS window
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
// prototype declarations
void displayCharArray(char charArray[], int sizeOfArray);
int main(int nNumberofArgs, char* pszArgs[])
{
    char charMyName[]={'S', 't', 'e', 'p', 'h', 'e', 'n'};
    displayCharArray(charMyName, 7);
    cout << endl;
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, 'n');
    cin.get();
    return 0;
}
// displayCharArray - display an array of characters
//                    by outputing one character at
//                    a time
void displayCharArray(char charArray[], int sizeOfArray)
{
    for(int i = 0; i< sizeOfArray; i++)
    {
        cout << charArray[i];
    }
}

The program declares a fixed array of characters charMyName. This array is passed to the function displayCharArray() along with its length.

This program works fine; however, it is inconvenient to pass the length of the array with the array itself. If you could come up with a rule for determining the end of the string of characters, you wouldn’t need to pass its length — you would know that the string was complete when you encountered the special rule that told you so.