Why adding a null character to an array of strings?

I know that we should use a null character to end a string array as follows:

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

But I just wanted to know why it is necessary to use a null character to complete such an array?

Also why we do not add a null charater to complete them: -

 char str1[5]="ANS"; 
+6
source share
2 answers

A NULL ending is what distinguishes a char array from a string (NULL-terminated char -array) in C. Most string management functions rely on NULL to know when a string is completed (and its job is executed) and will not work with simple char -array (for example, they will continue to work beyond the boundaries of the array and continue until they find NULL somewhere in memory - they often corrupt memory when it goes).

In C, 0 (an integer value) is considered logical FALSE - all other values ​​are considered TRUE. if , for and , whereas it uses 0 (FALSE) or nonzero (TRUE) to remove from branching or if loop. char is an integer type, the NULL character (\ 0) is actually and just a char with a decimal integer value of 0 - i.e. FALSE. This simplifies the execution of functions for operations such as manipulating or copying strings, since they can safely loop until the character he is working on is non-zero (i.e. TRUE) and stops when he encounters a NULL character ( i.e. FALSE) - since this means the end of the line. It makes very simple loops, since we don’t need to compare, we just need to know if it is 0 (FALSE) or not (TRUE).

Example:

     char source [] = "Test";  // Actually: T est \ 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.

+8
source

It is not important, but if you use any of the standard libraries, they all expect this.

+1
source

Source: https://habr.com/ru/post/946829/


All Articles