Character Arrays

Utilises the char data type followed by the chosen identifier and square brackets indicating the number of elements in the array:

 

char identifier[N] ; //array declaration

 

e.g.:    char myArray[7] ; //declaration of char array for 7 elements

 

Alternatively, if the number of elements in the array is ommited, the compiler will automatically size the array upon definition of the array contents.

 

e.g.:    char yourArray[] ; //declaration of char array for N characters

 

Values are assigned to the elements of a character array by using curly braces, and including a comma separated list of N 'single quoted' characters, where N is the number of elements indicated within the square brackets (which can be omitted to let the compiler automatically size the array):

 

e.g.:    char myCharArray[7] = {'L','a','v','e','r','d','a'} ;

 

or:    char myCharArray[] = {'L','a','v','e','r','d','a'} ;

 

 

As per numerical arrays, character arrays can also assign individual elements by index number. For example, say a character array is defined as follows: char myExample[] = {'D','i','v','e','r'} ; a specific character can be assigned like so: myExample[2] = 'n' ;

 

#include <iostream>
using namespace std;

int main () {

	char myCharArray[7] = {'L','a','v','e','r','d','a'} ;

	char yourCharArray[] = {'B','e','n','e','l','l','i'} ;

	for (int i = 0 ; i < 7 ; i++) {

		cout << "Element " << i << " of myCharArray: " << myCharArray[i] << endl ;
	}

	cout << "yourCharArray contains: " ;

	for (int i = 0 ; i < sizeof(yourCharArray) ; i++) {

		cout << yourCharArray[i] ;
	}

	cout << endl ;

	char myExample[] = {'D','i','v','e','r'} ;

	myExample[2] = 'n' ;

	for (int i = 0 ; i < sizeof(myExample) ; i++) {

		cout << myExample[i] ;
	}

	return 0;
}

Compile & Run:

Element 0 of myCharArray: L
Element 1 of myCharArray: a
Element 2 of myCharArray: v
Element 3 of myCharArray: e
Element 4 of myCharArray: r
Element 5 of myCharArray: d
Element 6 of myCharArray: a 

 

yourCharArray contains: Benelli

 

Diner

Leave a Reply