C++ Learning Resource Network!

 C++ Tutorials  >  Arrays  >  Strings

The most common use of one-dimentional array is a string. In C++, a string is defined as a character array terminated by a NULL character. A NULL character is represented as '\0'. The size of a character array should be at least one character longer than the string it is supposed to hold. This is because the last byte in a character array holds the string terminator ('\0').

For example, if you want to declare an array cWord that will hold a string of ten characters, the declation should be:

char cWord[11];

Initializing Strings

A string can be initialized when declared by specifying the value of some or all of its elements. The initialization at the time of declaration is possible only outside the function.

Direct initialization is possible in the following two ways:

char cStr1[10] = {'M','e','t','a','l','i','c','a','\0'};
char cStr2[10] = {"Metallica"};

In the first case, individual elements are moved into the array, and therefore it is essential to specify the string terminator explicitly. In the second case, the string terminator gets attached automatically since the string has been assigned to the array.

The following programs illustrates the initialization of arrays during declaration:

//Program 4.2
//This program demonstrates the initialization of arrays during declaration
char cArr[50] = {"the only thing constant in this world is change"};
void main()
cout<<"It is ironnical to note that"<<cArr<<endl;

Note that cArr is declared before the function main()

Array Address

The definition char cString[11];
defines an array cString to store ten elements and the string terminator. In the memory, cString actually refers to the starting position or address of the area which gets allocated for storing the elements of the array. Therefore, cString stores the address of cString[0], the first elements of the array. cString is therefore a pointer, but the address stored in cString is constant and cannot be changed.

For example, consider the following code:

char str[6] = "Hello";
void main()
cout<<"The string is "<<str<<endl;
cout<<"The string is "<<str<<endl;

The compiler will flag an error for the statement,
str++; because str is constant and cannot be changed.


| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.