What does '\0' mean here?

May 2, 2011 at 2:30am
int main(void)
{

char cAlphabet[] = {'I',' ', 'k','n','o','w',' ','a','l','l',' ','a','b','o','u','t',' ','p','r','o','g','r','a','m','i','n','g','!','\0'};
string sAlph(cAlphabet);
vector<string>sPhrase;
int size = sAlph.length();

................................

}

and


int main(void)
{

char cAlphabet[] = {'I',' ', 'k','n','o','w',' ','a','l','l',' ','a','b','o','u','t',' ','p','r','o','g','r','a','m','i','n','g','!'};
string sAlph(cAlphabet);
vector<string>sPhrase;
int size = sAlph.length();

................................

}

First one give size of 28, second one gives size of 39. Only difference is addition of \0 in the array of first program.

So What does \0 mean? and what does it do?

May 2, 2011 at 2:43am
'\0' is the null termination character. It marks the end of the string. Without it, the computer has no way to know how long that group of characters goes. When you print/copy/whatever a string, it just keeps printing/copying chars until it finds that null char... that's when it knows to stop.



EDIT:

On a side note, '\0' actually isn't special or anything, it's just an numerical escape sequence. IE: '\0' is just the literal number 0. Just like '\1' is the literal number 1.

I just felt like mentioning that for whatever reason. It's not important.

/EDIT
Last edited on May 2, 2011 at 2:45am
May 2, 2011 at 2:48am
its quite useful if you want to iterate through each character of a string by just going to the next character until a \0 is found. also note that when using double quotes "" they automatically add the \0. so
 
char cAlphabet[] = "I know all about programming!";


is the same as

 
char cAlphabet[] = {'I',' ', 'k','n','o','w',' ','a','l','l',' ','a','b','o','u','t',' ','p','r','o','g','r','a','m','i','n','g','!','\0'};


and nowhere near as annoying to type

p.s. you mispelled programming :o
Last edited on May 2, 2011 at 2:49am
Topic archived. No new replies allowed.