Creation of the character array syntax:
See the below sample that we can declare the names or words in the character array
1 |
char szExample[] = {‘c’, ‘o’, ‘d’, ‘i’, ‘n’, ‘z’}; |
Storing Sequences in Arrays
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> using namespace std; void ShowArray(char stringArray[], int iSize); int main(int nArg, char* pszArgs[]) { char szExample[] = {‘c’, ‘o’, ‘d’, ‘i’, ‘n’, ‘z’}; ShowArray(szExample , 6); cout << "\n"; return 0; } // ShowArray - display an array of characters // by outputing one character at // a time void ShowArray(char stringArray[],int iSize) { for(int i = 0; i< iSize; i++) { cout << stringArray[i]; } } |
The program declares a fixed array of characters szExample containing the list of characters.
This array is passed to the function ShowArray() along with its length. The ShowArray()
the function is identical to the displayArray() function along with the length.
The output of the above program is
1 |
codinz |
Creating a string of characters
In C++ the character array ends with the ‘\0’ to know the end of the array
See the below example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <cstdio> #include <cstdlib> #include <iostream> #include <string> using namespace std; void ShowArray(char StrArray[]); int main(int nNumberofArgs, char* pszArgs[]) { char szExample[] = {‘c’, ‘o’, ‘d’, ‘i’, ‘n’, ‘z’}; ShowArray(szExample); system ("PAUSE"); return 0; } // ShowArray - display a character string // one character at a time void ShowArray(char StrArray[]) { for(int i = 0; StrArray[i] != '\0'; i++) { cout << StrArray[i]; } } |
The declaration of szExample declares the character array with the extra
null character \0 on the end. The ShowArray program iterates through
the character array until a null character is encountered.
The function ShowArray () is simpler to use than its ShowArray()
predecessor because it is no longer necessary to pass along the length of the
character array. This secret handshake of terminating a character array with
a null is so convenient that it is used throughout C++ language. C++ even gives
such an array a special name.
A string of characters is a null-terminated character array. Confusingly enough,
this is often shortened to simply string, even though C++ defines the separate
type string.