the null character

Feb 19, 2009 at 5:15pm
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:20pm
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:
 
cout << "hello\0world";

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:25pm
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
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:
HelloÌÌÌÌÌÌÌÌÌÌÌ


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 6:58pm
Please be aware that Bazzy's example is OS- and compiler-dependant. YRMV.
Feb 19, 2009 at 9:51pm
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
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 6:04pm
Only when those arrays are initialized with the syntax Bazzy used above:
char hello[]={'H','e','l','l','o','\0'};
You don't have to if you use this syntax:
1
2
3
char *hello="Hello";
//or
char hello[]="Hello";
Feb 20, 2009 at 6:10pm
Everything with double quotes already have a null character at the end
Topic archived. No new replies allowed.