Arrays of Characters

Re-Introduction to Characters

In our second lesson, we had a brief introduction to arrays of characters and strings. So far, we have avoided using them whenever we did not have to. As it happens, strings are the most used items of computers. In fact, anything the user types is a string. It is up to you to convert it to another, appropriate, type of your choice. This is because calculations cannot be performed on strings. On the other hand, strings can be a little complex, which is why we wanted to first know how to use the other types and feel enough comfortable with them.

Consider a name such as James. This is made of 5 letters, namely J, a, m, e, and s. Such letters, called characters, can be created and initialized as follows:

char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

To display these characters as a group, you can use the following:

cout << "The name is " << L1 << L2 << L3 << L4 << L5;

Here is such a program: 

#include <iostream>
using namespace std;

int main()
{       
    char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

    cout << "The name is " << L1 << L2 << L3 << L4 << L5;
}

This would produce:

The name is James

Declaring and Initializing an Array of Characters

When studying arrays, we were listing the numeric members of the array between curly bracket. Here is an example:

int Number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

Because a character is initialized by including it in single-quotes, when creating an array of characters, to initialize it, you must also include each letter accordingly. A name such as James can be initialized as follows:

char Name[6] = { 'J', 'a', 'm', 'e', 's' };

As done with other arrays, each member of this array of characters can be accessed using its index. Here is an example:

#include <iostream>
using namespace std;

int main()
{
    char Name[6] = { 'J', 'a', 'm', 'e', 's' };

    cout << "The name is " << Name[0] << Name[1] << Name[2]
         << Name[3] << Name[4];
}

The C/C++ provides another alternative. It allows you to declare and initialize the array as a whole. To do this, include the name in double-quotes. With this technique, the curly brackets that delimit an array are not necessary anymore. Here is an example:

char Name[12] = "James";

With this technique, the item between the double-quotes is called a string. It is also referred to as the value of the string or the value of the variable.

When declaring and initializing an array of characters, the compiler does not need to know the number of characters of the string. In fact, you can let the compiler figure it out. Therefore, you can leave the square brackets empty:

char Name[] = "James";

After declaring such an array, the compiler would count the number of characters of the variable, add one more variable to it and allocate enough space for the variable. The character added is called the null-terminated character and it is represented as \0. Therefore, a string such as James would be stored as follows:

J a m e s \0

This something you will need to remember regularly.

Color = Black

Country = Swaziland
  

Streaming an Array of Characters

Like any other variable, before using a string, you must first declare it, which is done by type the char keyword, followed by the name of the variable, followed by square brackets. When declaring the variable, if/since you do not know the number of characters needed for the string, you must still provide an estimate number. You can provide a value large enough to accommodate the maximum number of characters that would be necessary for the variable. For a person's name, this could be 20. For the title of a book or a web page, this could be longer. Here are examples:

char Name[20];

char BookTitle[40];

char WebReference[80];

char WeekDay[4];

To request the value of an array of characters, use the cin extractor just like you would proceed with any other variable, without the square bracket. Here is an example:

char WeekDay[12];



cout << "Enter today's name: ";

cin >> WeekDay;

To display the value of an array of characters, use the cout extractor as we have used it with all other variables, without the square brackets. Here is an example:

#include <iostream>

using namespace std;



int main()

{

    char WeekDay[12];

    char EndMe[] = "\n";



    cout << "Enter today's name: ";

    cin >> WeekDay;



    cout << "Today is " << WeekDay;



    cout << EndMe;

    

    return 0;

}

Here is an example of running the program:

Enter today's name: Thursday

Today is Thursday

 

Multidimensional Arrays of Characters

C/C++ treats arrays of characters differently than it does the other arrays. For example, we have learned to declare a two-dimensional array of integers as follows:

int Number[2][6] = { { 31, 28, 31, 30, 31, 30 },

                     { 31, 31, 30, 31, 30, 31 } };

This variable is in fact two arrays and each array contains 6 integers. For a string, if you want to declare a two-dimension array of characters, the first dimension specifies the number of string in the variable. The second dimension specifies the number of characters that each string can hold. Here is an example:

char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };

In this case, the StudentName variable is an array of 4 strings and each string can have a maximum of 9 characters (+1 for the null-terminated character). To locate a string on this variable, type the name of the array followed by its index, which is the index of the column. This means that the first string of the StudentName array can be accessed with StudentName[0]. The second would be StudentName[1], etc. This allows you to display each string on the cout extractor:

#include <iostream>

using namespace std;



int main()

{

    char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };



    cout << "Student Names";

    cout << "\nStudent 1: " << StudentName[0];

    cout << "\nStudent 2: " << StudentName[1];

    cout << "\nStudent 3: " << StudentName[2];

    cout << "\nStudent 4: " << StudentName[3];

    

    return 0;

}

This would produce:

Student Names

Student 1: Hermine

Student 2: Paul

Student 3: Gertrude

Student 4: Leon

When declaring and initializing such an array, the compiler does not need to know the number of strings in the array; it can figure it out on its own. Therefore, you can leave the first pair square brackets empty. If you are only declaring the array but cannot initialize, then you must specify both dimensions.

To request the values of the array, once again, locate each member using its index. Here is an example:

Enther the first name of each player

Student 1: Walter

Student 2: Guy

Student 3: Celestin

Student 4: Maurand

Student 5: Phillipe



Student Names

Student 1: Walter

Student 2: Guy

Student 3: Celestin

Student 4: Maurand

Student 5: Phillipe

There are two alternatives to solve this problem: you can use the getline() function from the basic_string library or you can use the gets() function from the C language.

Pointers and Arrays of Characters

 

Declaring a Pointer to Characters

Earlier, we declared an array as follows:

char EndMe[] = "";

The name of the variable is a pointer to the beginning of the array. For this reason, the name of the reason is sufficient to locate its value. Since in this case we do not specify the number of characters in the array, we can also just use a pointer to the array as the beginning of the array. The array can therefore be declared as follows:

char *EndMe = "";

Once again, to display the value of such an array, simply call its name on the cout extractor:

#include <iostream>

using namespace std;



int main()

{

    char *EndMe = "";



    cout << EndMe;

    

    return 0;

}

To request the value of an array of characters from the user, you can declare a pointer to char and initialize it with an estimate number of characters using the new operator. Here is an example:

#include <iostream>

using namespace std;



int main()

{

    char *StudentName = new char[20];



    cout << "Enter Sudent First Name: ";

    cin >> StudentName;



    cout << "\nStudent First Name: " << StudentName;   

    

    return 0;

}

Here is an example of running the program:

Enter Sudent First Name: Charlotte



Student First Name: Charlotte

 

 

Declaring and Initializing an Array of Characters

From our study and use of characters, we have seen that, to declare a character variable, we can use any C++ valid name. To initialize a character variable, type it between single-quotes. Here is an example:

char Answer = ‘y’;

To declare an array of characters, type the char keyword followed by the techniques we used to declare the other arrays. The syntax is:

char ArrayName[Dimension];

The char keyword lets the compiler know that you are declaring a variable of character type. The square brackets let the compiler know that you are declaring an array. The name of the array follows the same rules and suggestions we have used for the other variables. Once again, the dimension of the array could be an approximation of the number of characters you anticipate.

To initialize an array of characters, you use the curly brackets. Each character must be enclosed in single-quotes. If you know the characters you will be using to initialize the array, you should omit specifying the dimension. Here is an example:

char Color[] = { 'B', 'l', 'a', 'c', 'k' };

Another technique used to initialize an array of characters is to type the group of characters between double-quotes. Since you know the array, let the compiler figure out its dimension. Here is an example:

char Country[] = "Swaziland";

Any of these two techniques would allow you to display the string using the cout operator. The compiler already knows the dimension and the contents of the array: 

#include <iostream> 

using namespace std;



int main()

{

	char Color[] = { 'B', 'l', 'a', 'c', 'k' };

	char Country[] = "Swaziland";



	cout << "Color = " << Color << endl;

	cout << "Country = " << Country;



	return 0;

}

This would produce:

Color = Black

Country = Swaziland

Requesting an Array of Characters

Instead of initializing an array, sometimes you will have to wait until the program is running, to assign a value to the array. First, you must declare the array, specifying an approximate dimension. To request the value of an array of characters, use the cin operator, specifying only the name of the array. Here is an example:

#include <iostream>

using namespace std;



int main()

{

	char FirstName[20];

	char MI;

	char LastName[20];



	cout << "The following pieces of information are need"

		 << "to complete your application\n";

	cout << "First Name: ";

	cin >> FirstName;

	cout << "Middle Initial: ";

	cin >> MI;

	cout << "Last Name: ";

	cin >> LastName;

	

	cout << "\nMember Information";

	cout << "\nFull Name: " << FirstName << " " << MI << ". " << LastName;



	return 0;

}

Here is an example of running the program:

The following pieces of information are need

to complete your application



First Name: Michael

Middle Initial: J

Last Name: Callhoun



Member Information

Full Name: Michael J. Callhoun

If you use the “normal” cin operator above, the compiler expects the user to type a one-word string from the keyboard. If you want the user to type text that includes space, you should use the cin::getline() function. The syntax of the getline() function is:

cin.getline(ArrayName, Dimension, Delimiter=’\n’);

The array name is the one you used when declaring the array. The dimension is the same value you set when declaring the variable. The delimiter is an optional character that the user would type to specify the end of the string. By default, the compiler expects the user to press Enter to end the string. Logically, the following program illustrates the use of the cin::getline() function to request text strings from the user:

#include <iostream>

using namespace std;



int main()

{

	char Author[40];

	char Title[40];

	char Publisher[50];



	cout << "Book Collection\n";

	cout << "Author: ";

	cin.getline(Author, 40);

	cout << "Title: ";

	cin.getline(Title, 40);

	cout << "Publisher: ";

	cin.getline(Publisher, 50);

	cout << "\nBook Information";

	

	cout << "\nAuthor Name: " << Author

	     << "\nBook Title: " << Title

	     << "\nPublisher: " << Publisher;



	return 0;

}

Here is an example of running the program:

Book Collection

Author: Elliot Mendelson

Title: 3000 Solved Problems In Calculus

Publisher: McGraw Hill



Book Information

Author Name: Elliot Mendelson

Book Title: 3000 Solved Problems In Calculus

Publisher: McGraw Hill

Arrays of Characters and Pointers

Declaration of an Array of Characters

We have learned to declare an array of characters using the square brackets and to initialize it using the assignment operator. By not specifying the dimension of the array, we are relying on the compiler to find out how many items the array has. Here is an example:

#include <iostream>

using namespace std;



int main()

{

	char Country[] = "Republique d'Afrique du Sud";



	cout << "Country Name: " << Country << "\n\n";



	return 0;

}

As you can see for this example, to display the value of the Country variable, although it is an array, all the compiler needs is the name. How come? As it happens, when you create an array of characters, such as the Country variable above, the name of the array is the same as Country[0]. In other words, it represents the beginning of the space memory occupied by the variable. As we saw when studying pointers, this beginning of the space occupied by a variable is referred to as its address. Because the compiler knows this and is able to figure it out, C++ provides another solution. Instead of declaring the array with empty square brackets, since we are in fact referring to the address of the variable, we can declare it a pointer to char. Therefore, the above program can be written as follows:

#include <iostream>

using namespace std;



int main()

{

	char *Country = "Republique d'Afrique du Sud";



	cout << "Country Name: " << Country << "\n\n";

	return 0;

}

Both programs would produce the same result. There is something important to know about this new version. The asterisk on the name informs the compiler that it should consider the Country variable starting at its address and up. If you do not initialize the variable, the compiler would not complain as long it is now able to locate the variable. Based on this, you can initialize the variable when you are ready and not necessarily when you declare it. Keep in mind that this theory is valid only for an array of characters; for example the following program will not compile:

#include <iostream>

using namespace std;



int main()

{

	double *Value;



	Value = 12.55;



	cout << "Value = " << Value;



	return 0;

}

On the other hand, the following declaring of an array of characters and its later initialization is perfectly legal:

#include <iostream>

using namespace std;



int main()

{

	char *Country;



	Country = "Republique d'Afrique du Sud";



	cout << "Country Name: " << Country << "\n\n";

	return 0;

}

Dynamic Arrays of Characters

A dynamic object is one whose memory is requested and used only when needed. Such objects are created using the new operator. In the same way, to dynamically create an array, you use the new operator. To do this, the variable must be declared a pointer to char, as done above. Then assign the new char expression that followed by a pair of square brackets. In the square brackets, specify the desired dimension of the array. An example would be:

char *Country = new char[20];

After declaring such a variable, you can assign it any value you want. Here is an example:

#include <iostream>

using namespace std;



int main()

{

	char *Country = new char[20];



	Country = "Equatorial Guinea";

	cout << "Country Name: " << Country;



	cout << "\n\n";

	return 0;

}

Passing an Array of Characters

Like other regular arrays, you can pass an array of characters to a function or you can return an array of characters from a function. To pass an array of characters to a function, when declaring and when defining the function, provide the name of the array followed by empty parentheses. When calling the function, provide only the name of the argument you are passing. Here is an example:

#include <iostream>

using namespace std;



void ShowCountry(const char S[])

{

	cout << "Country Name: " << S << "\n\n";

}



int main()

{

	char Country[] = "Republique d'Afrique du Sud";



	ShowCountry(Country);

	return 0;

}

Alternatively, as we have learned that you can also declare an array of characters using a pointer to char, when declaring and when defining the array, you can provide the argument as a pointer to char. When calling the function, provide the argument of the function by specifying only the name of the argument:

#include <iostream>

using namespace std;



void ShowCountry(const char *S)

{

	cout << "Country Name: " << S << "\n\n";

}



int main()

{

	char *Country = "Republique d'Afrique du Sud";



	ShowCountry(Country);



	return 0;

}

Returning an array of Characters

Just as you can pass an array of characters to a function, you can also return such an array from a function. To do this, the function must be declared and defined as a pointer to char. Here is an example:

char *GetFirstName();

When calling such a function, you are requesting its value and want to assign it to a variable, make sure that the variable is also declared as pointer to char. Here is an example:

#include <iostream>

using namespace std;



char *GetFirstName()

{

	char *FName = new char[20];



	cout << "Enter First Name: ";

	gets(FName);



	return FName;

}



int main()

{

	char *FirstName;



	FirstName = GetFirstName();

	cout << "First Name: " << FirstName << "\n\n";

	return 0;

}

Multidimensional Arrays of Characters

Double-Dimensional Arrays Declaration

Once again, an array of characters is different from an array of other regular data types. Imagine you want to create various lists of countries. You would declare such an array as follows:

char Country[3][8];

Unlike other data types, it is important to know what each dimension represents. This array initiates 3 lists of countries. Each country can have up to 8 letters. In other words, the first dimension represents the number of items that make up the list. It is as if you had declared an array of flowing-point numbers as double Distance[5] which represents a series of 5 distances. The second dimension of an array of characters represents the maximum number of characters that each item can have.

To initialize a 2-dimensional array, assign an opening and a closing curly brackets to it. Inside of the curly brackets, provide each item between double-quotes. Here is an example:

#include <iostream>

using namespace std;



int main()

{

	char Country[3][20] = { "Afrique du Sud", "Australie", "Zimbabwe" };



	return 0;

}

Make sure that the number of items of your list is equal to or less than the first dimension. If this condition is not met, the compiler would display an error. For example, the following program will not compile because the declaration of the array specifies that the array is made of three items but is initialized with 6:

#include <iostream>

using namespace std;



int main()

{

	char Country[3][20] = { "Afrique du Sud", "Australia", "Zimbabwe",

			     "Sri Lanka", "Yemen", "El Salvador" };



	return 0;

}

In the same way, make sure that each item of the array has a number of characters (or letters) that is equal to or less than the second dimension. The following program will not compile because two items of the array (the 1st and the last) have more than 10 letters after you had declared that the maximum number of letters of each item of the arrays would be 10 characters:

#include <iostream>

using namespace std;



int main()

{

	char Country[6][10] = { "Afrique du Sud", "Australia", "Zimbabwe",

	                        "Sri Lanka", "Yemen", "El Salvador" };



	return 0;

}

To access an item of the 2-dimensional array of characters, provide its name followed by its index. The index here is from the first dimension because the first dimension specifies the number of items of the array. For example, you can access the 3rd item of the above Country array with Country[4]. The compiler does not need the dimension of each item to display it. Here is an example:

#include <iostream>

using namespace std;



int main()

{

	char Country[6][15] = { "Afrique du Sud", "Australia", "Zimbabwe",

	                        "Sri Lanka", "Yemen", "El Salvador" };



	cout << "Countries Names";

	cout << "\nCountry 1: " << Country[0];

	cout << "\nCountry 2: " << Country[1];

	cout << "\nCountry 3: " << Country[2];

	cout << "\nCountry 4: " << Country[3];

	cout << "\nCountry 5: " << Country[4];

	cout << "\nCountry 6: " << Country[5];



	cout << "\n\n";

	return 0;

}

This would produce:

Countries Names

Country 1: Afrique du Sud

Country 2: Australia

Country 3: Zimbabwe

Country 4: Sri Lanka

Country 5: Yemen

Country 6: El Salvador

In the same way, you can use a for loop to scan the array, accessing each member by its position. Here is an example:

#include <iostream>

using namespace std;



int main()

{

	char Country[6][15] = { "Afrique du Sud", "Australia", "Zimbabwe",

	                        "Sri Lanka", "Yemen", "El Salvador" };



	cout << "Countries Names";

	for(int i = 0; i < 6; ++i)

		cout << "\nCountry " << i + 1 << ": " << Country[i];



	cout << "\n\n";

	return 0;

}

When you declare a two-dimensional array, yo do not have to know how many items the array is made of but you must know the maximum number of characters that each item can be mad of. This property of arrays can be used to leave the first square brackets empty:

#include <iostream>

using namespace std;



int main()

{

	char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe",

		              "Sri Lanka", "Yemen", "El Salvador" };



	cout << "Countries Names";

	for(int i = 0; i < 6; ++i)

		cout << "\nCountry " << i + 1 << ": " << Country[i];



	cout << "\n\n";

	return 0;

}

We saw earlier that, using a pointer to char, you do not have to specify the number of characters that composes an array. For a 2-dimensional array, you can let the compiler figure out how many items the array uses. To do this, when declaring the array, precede the name of the array with an asterisk. This will allow the compiler to locate the address of the first item and take over from there. Based on this, the above array can be declared as follows:

char *Country[15] = { "Afrique du Sud", "Australia", "Zimbabwe",

                      "Sri Lanka", "Yemen", "El Salvador" };

We also saw earlier that the name of an represents the address of the variable. In the same way, you do not have to find the item that has the highest number of characters and specify it as the second dimension of the array. You can let the compiler figure out this by letting the square brackets empty. By your initializing the array, the compiler would figure out how much space each item needs. Therefore, the above array can be declared as follows:

#include <iostream>

using namespace std;



int main()

{

	char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe",

		                "Sri Lanka", "Yemen", "El Salvador" };



	cout << "Countries Names";

	for(int i = 0; i < 6; ++i)

		cout << "\nCountry " << i + 1 << ": " << Country[i];



	cout << "\n\n";

	return 0;

}

Two-Dimensional Arrays of Characters and Functions

When declaring and when defining a function that takes as argument a 2-dimensional array, the argument is passed with two pairs of square brackets. The first square bracket should be left empty although you are allowed to specify its dimension. This first pair of square brackets lets the compiler know the argument represents a group of strings. The second pair of square brackets must have the maximum characters that each item of the array has. Such a function can be declared and defined as follows:

void ShowCountries(char S[][15]);

When calling such a function, provide only the name of the array. The compiler can figure out the rest by referring to the definition of the function (of course, this is still your responsibility). Here is an example:

#include <iostream>

using namespace std;



void ShowCountries(char S[][15])

{

	cout << "Countries Names";



	for(int i = 0; i < 3; ++i)

		cout << "\nCountry " << i + 1 << ": " << S[i];

}



int main()

{

	char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe",

                                "Sri Lanka", "Yemen", "El Salvador" };



	ShowCountries(Country);



	cout << "\n\n";

	return 0;

}

If you expect the function to also process the (whole) array, you can pass a second argument that would hold the actual number of items that composes the array passed as argument. Here is an example:

#include <iostream>

using namespace std;



void ShowCountries(char S[][15], const int n)

{

	cout << "Countries Names";



	for(int i = 0; i < n; ++i)

		cout << "\nCountry " << i + 1 << ": " << S[i];

}



int main()

{

	char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe",

                                "Sri Lanka", "Yemen", "El Salvador" };



	ShowCountries(Country, 6);



	cout << "\n\n";

	return 0;

}

You can also pass the argument as a pointer to char after declaring the array as such. This, of course, allows the compiler to better manage memory because it can figure out how many items are in the array and how much space each item needs.

To pass an array as a pointer to char, when declaring and when defining the function, precede the name of the argument with an asterisk and type an empty pair of square brackets on the right side of the name of the argument. You can call this function the same way we did above:

#include <iostream>

using namespace std;



void ShowCountries(char *S[], const int n)

{

	cout << "Countries Names";



	for(int i = 0; i < n; ++i)

		cout << "\nCountry " << i + 1 << ": " << S[i];

}



int main()

{

	char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe",

                             "Sri Lanka", "Yemen", "El Salvador" };



	ShowCountries(Country, 6);



	cout << "\n\n";

	return 0;

}

Alternatively, when declaring and when defining the function, you can specify that the argument is a pointer to char:

#include <iostream>

using namespace std;



void ShowCountries(char **S, const int n)

{

	cout << "Countries Names";



	for(int i = 0; i < n; ++i)

		cout << "\nCountry " << i + 1 << ": " << S[i];

}



int main()

{

	char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe",

                        "Sri Lanka", "Yemen", "El Salvador" };



	ShowCountries(Country, 6);



	cout << "\n\n";

	return 0;

}
 

Previous Copyright © 2000-2026, FunctionX Wednesday 24 September 2025, 17:16 Next