Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why adding a Null Character in a String array? [duplicate]

I know that we have to use a null character to terminate a string array like this:

char str[5] = { 'A','N','S','\0' };

But I just wanted to know why is it essential to use a null character to terminate an array like this?

Also why don't we add a null charater to terminate these :-

char str1[5]="ANS";
like image 791
Anurag-Sharma Avatar asked Jun 08 '13 02:06

Anurag-Sharma


1 Answers

The NULL-termination is what differentiates a char array from a string (a NULL-terminated char-array) in C. Most string-manipulating functions relies on NULL to know when the string is finished (and its job is done), and won't work with simple char-array (eg. they'll keep on working past the boundaries of the array, and continue until it finds a NULL somewhere in memory - often corrupting memory as it goes).

In C, 0 (the integer value) is considered boolean FALSE - all other values are considered TRUE. if, for and while uses 0 (FALSE) or non-zero (TRUE) to determent how to branch or if to loop. char is an integer type, an the NULL-character (\0) is actually and simply a char with the decimal integer value 0 - ie. FALSE. This make it very simple to make functions for things like manipulating or copying strings, as they can safely loop as long as the character it's working on is non-zero (ie. TRUE) and stop when it encounters the NULL-character (ie. FALSE) - as this signifies the end of the string. It makes very simple loops, since we don't have to compare, we just need to know if it's 0 (FALSE) or not (TRUE).

Example:


    char source[]="Test";  // Actually: T e s t \0 ('\0' is the NULL-character)
    char dest[8];

    int i=0;
    char curr;

    do {
       curr = source[i];
       dest[i] = curr;
       i++;
       } while(curr); //Will loop as long as condition is TRUE, ie. non-zero, all chars but NULL.

like image 81
Baard Kopperud Avatar answered Sep 28 '22 06:09

Baard Kopperud