the null character

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
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
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.
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
Please be aware that Bazzy's example is OS- and compiler-dependant. YRMV.
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'
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
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";
Everything with double quotes already have a null character at the end
Topic archived. No new replies allowed.