Trailing NULL in an array in C

I have a simple question.
Why it is necessary to consider the terminating zero in an array of characters (or just a string), and not an array of integers. So when I want the string to contain 20 characters, I need to declare char string[21];. When I want to declare an array of integers containing 5 digits, then int digits[5];enough. What is the reason for this?

+3
source share
9 answers

You do not need to interrupt the array charwith NULLif you do not want to, but when using them to represent a string, you need to do this because C uses zero-terminated strings to represent your strings. When you use functions that work with strings (for example, strlenfor the length of a string or using printfto output a string), these functions will read the data until it is encountered NULL. If not, then you are likely to encounter buffer overflows or similar problems with access violations / segmentation.

In short: how C represents string data.

+7
source

Zero terminators are required at the end of strings (or character arrays) because:

  • . ( .)
  • NUL (ASCII 0x00) . , EOF ASCII .

, , ; , . , - , .

+4

, , .

, printf %s, :

int i = 0;
while(input[i] != '\0') {
   output(input[i]);
   i++;
}

.

+3

, C ascii nul. ( , NULL.)

, nul nul . .

, : . "20- " 21- , .

+3

, -, , C.

C , NUL, . "string literals" , strcpy printf .. , C , .

-, , - , , , : , . C - , - Bell Labs , "" , NUL, , . ( .)

+3

, . . . Ints c , .

+3

, 21 . , ( ) , . .

+2

- , C

+1

- NUL - , ! , , . , , .

, - (, , ).

+1

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


All Articles