Char array variations
Learning character array variations and need for null terminator
- Concept of character arrays.
- Character array initialisation.
- Anomalies of character array initialisation.
- Concept of null terminated strings, also called the c-style strings.
- Behaviour of cout in printing null terminated and non-null terminated character arrays.
- Cases where compiler automatically puts null character at the end of character arrays.
using namespace std;
cout<<"array 1 contains "<<ca1<<endl;
cout<<"array 2 contains "<<ca2<<endl;
cout<<"array 3 contains "<<ca3<<endl;
cout<<"array 4 contains "<<ca4<<endl;
cout<<"array 1 by individual characters = "
Test it !
Test it !
Before using this you should have copied the code by selecting the entire code and pressing cntrl-c. (Line numbers will not come in the copied code). After that open any of the service and press cntrl-v to paste in the given code area. Needs a bit of tweaking as per the link.
Initialisation character array with individual characters. Here 4 initialising character F, A, C and E are given and array size will automatically become 4 characters.
Here array size is predefined and only 4 characters can be given for initialisation. If you give more than that program will not compile.
Here array size has been defined as 5 and only 4 initialisation characters have been given. In this 1 extra space of putting null () character is there. This will automatically be done by the compiler and ca3 will be a neatly printable null character terminated string of C language style of strings.
Here string initialisation has been done with a 4 character string literal. One extra space for null character will automatically be assigned by the compiler.
cout<<“array 1 contains “<<ca1<<endl;
This will print FACE followed by few junk characters as null termination is not proper.
cout<<“array 2 contains “<<ca2<<endl;
This will print NOSE followed by few junk characters as null termination is not proper in this case also as the space for 5th character is not there..
cout<<“array 3 contains “<<ca3<<endl;
This will print NOSE properly as 5th character storage space we have provided and compiler has an opportunity to terminate it properly with the null character.
cout<<“array 4 contains “<<ca4<<endl;
This will print CHIN properly as string literal has been used for initialisation and compiler has its own choice of creating extra space for null character.
cout<<“array 1 by individual characters = “
This will print FACE as individual characters are now being picked from the array and are being displayed one after the other.
- In C++ use of string type is recommended in place of null terminated character array.
- In C++ Char array is used mainly when it is convenient to store a series of individual characters for the purpose of some character oriented data.
Suggested Filename(s): chararr.cpp, chararraytypes.cpp
sunmitra| Created: 4-Dec-2017 | Updated: 11-Jan-2018|