Tuesday, 23 December 2014

Character arrays and String arrays in C++ with examples

Character arrays and String arrays in Cpp with examples:

Creation of the character array syntax:

See the bleow sample that we can declare the names or words in the character array
char szExample[] = {‘F’, ‘i’, ‘r’, ‘s’, ‘t’, ‘s’, ‘m’, ‘p’, ‘l’, ‘e’};

Storing Sequences in Arrays

#include <iostream>
using namespace std;
void ShowArray(char stringArray[], int iSize);
int main(int nArg, char* pszArgs[])
  char szExample[] = {'F', 'i', 'r', 's', 't', 's', 'm', 'p', 'l', 'e'};
  ShowArray(szExample, 10);
  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()
function is identical to the displayArray() function along with the length.

The output of the above program is

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
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
void ShowArray(char StrArray[]);
int main(int nNumberofArgs, char* pszArgs[])
char szExample[] = {'F', 'i', 'r', 's', 't', 's', 'm', 'p', 'l', 'e'};
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.

No comments: