Feb 19, 2009 at 5:15pm Feb 19, 2009 at 5:15pm UTC
I am reading the character sequences section of this tutorial here.
It has mentioned the null character '0' but it doesn't have any example.
please give me a simple example of null character.
Last edited on Feb 19, 2009 at 5:16pm Feb 19, 2009 at 5:16pm UTC
Feb 19, 2009 at 5:20pm Feb 19, 2009 at 5:20pm UTC
The null character
'\0'
is used to terminate C strings
eg:
char hello[6] = "Hello" ;
is the same as
char hello[6] = { 'H' , 'e' , 'l' , 'l' , 'o' , '\0' };
if you try this code:
It will show only "hello" as when a null character is found the string is terminated
'\0'
has the same value as
char ( 0 )
Last edited on Feb 19, 2009 at 5:23pm Feb 19, 2009 at 5:23pm UTC
Feb 19, 2009 at 5:25pm Feb 19, 2009 at 5:25pm UTC
eg: char hello[6] = "Hello"; is the same as char hello[6] = { 'H', 'e', 'l', 'l', 'o', '\0' };
why did we put null character in this code because we can put less then the arrays element.
Feb 19, 2009 at 5:38pm Feb 19, 2009 at 5:38pm UTC
Using
"Hello"
the null character is automatically added, using
{ 'H' , 'e' , 'l' , 'l' , 'o' , '\0' }
you have to put it or when diplaying the array you will see all characters until the next '\0'
eg:
1 2
char hello[]={'H' ,'e' ,'l' ,'l' ,'o' };
cout << hello;
Result:
Other example:
1 2 3
char hello[]={'H' ,'e' ,'l' ,'l' ,'o' };
char world[] = {'W' ,'o' ,'r' ,'l' ,'d' };
cout << world;
Result:
WorldÌÌÌÌÌÌÌÌÌÌÌHelloÌÌÌÌÌÌÌÌÌÌÌ
hello was stored in memory just a few bytes after
world and both of them are shown as there aren't null characters between them
Last edited on Feb 19, 2009 at 5:43pm Feb 19, 2009 at 5:43pm UTC
Feb 19, 2009 at 6:58pm Feb 19, 2009 at 6:58pm UTC
Please be aware that Bazzy 's example is OS- and compiler-dependant. YRMV.
Feb 19, 2009 at 9:51pm Feb 19, 2009 at 9:51pm UTC
That was just to show that without '\0' you get strange result, often with the same compiler and OS I get different outputs when I forget a '\0'
Feb 20, 2009 at 5:25pm Feb 20, 2009 at 5:25pm UTC
does it mean that we have to use null character always with an array as it gives strange result without null character?
Last edited on Feb 20, 2009 at 5:26pm Feb 20, 2009 at 5:26pm UTC
Feb 20, 2009 at 6:10pm Feb 20, 2009 at 6:10pm UTC
Everything with double quotes already have a null character at the end