String declaration and initialisation – CSKC
Sign In

Search

Code Learning #CPP#2545    siteicon   siteicon  

String declaration and initialisation

String declaration as character arrays an initialising them as individual character literals or as string literals.

Learning Objectives

  • Learning ways to declare and initialise the strings as character arrays.
  • Learning the concept of null character as end character of the string.

Source Code

TC++ #2545

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

char s1[3];
Here we are declaring a character array with a size of 3 locations.
s1[0]=’C’;s1[1]=’+’;s1[2]=’+’;
We are populating each character with a character literal.
cout<<s1<<endl;
We are printing the char array as a one string. Since the last character here is not a null character () so we may get some junk characters after the third character.

char s2[4];
Here we are declaring a 4 character character array to be used as a 3 character string.
s2[0]=’C’;s2[1]=’+’;s2[2]=’+’;s2[3]=”;
First three characters we fill the required characters of the string and the last character we fill as the null () character.
cout<<s2<<endl;
We print the string and it will get printed correctly.

char s3[]=”C++”;
Here we are not pre-deciding the size of the character array but we are filling it with a string literal. The number characters in the given string literal become the size of the array. Actually it takes one more space for the null character.
cout<<s3<<endl;
The string will print well.

Notes

  • The concept of null terminated character is now getting phased out in favour of string class use as introduced in c++, but it remains an important concept as c++ is still backward compatible with C code and is likely to remain so in future as well.


Suggested Filename(s): st-dec-init.cpp, strdec.cpp



Share

Created: 12-Jan-2018 19:49 | Updated: 12-Jan-2018 20:02|