Doubt in the length of string array

Hello, If we have a array of type char and I have entered a a string in that array using cin.getline ( ) method. Will the compiler add \0 by itself ? Or how the program will run Please explain me ? My main focus in this doubt is on null character ( \0 ) that how it is added and when it is added, What exactly happens at the memory level ?

hello @yashsharma4304

when u give string(assuming char array) as input in runtime then \0 is automatically get added in the last of string.
in memory level.
let say abc is the string u have given in input .
then it will look something like
a (block1) | b (block2) | c (block3) | \0 (block4)

Ok so suppose I have declared the array as :
char a[10];

and I entered exactly 10 characters then where will the null character go ? Will the size of array in that case is 11 instead of 10 ?

in this case ur array capacity is 10 that means u can input atmax 9 character and 10th character will be \0.

if u will give 10 character in input then we dont have any space left in our array for \0 hence it will not get appended in the char array.
and when u will print such array then u will notice some garbage character as well.

so the counclusion is u want to input n characters in input then declare ur array of size n+1 (+1 to accomodate \0)

1 Like

I have one more query regarding strlen( ). This method prints the length of string then does it mean that it will count the characters until it finds \0. As it finds \0 it will not count it in the length. Is this right ?

yeah \0 never get counted in strlen function

1 Like