Why is a zero limiter needed?

I have been teaching myself C ++ over the past two days to prepare for the first year as the main CS. I am now on the lines of C-style and am wondering what a null terminator point is.

I understand that this is necessary, but I think I just don’t understand why the line will not just end on the last char.

+4
source share
4 answers

I just basically don’t understand why the line will not just end on the last char.

There are several ways to find out where the "last char" is:

  • Keep the number of characters in a string separate from the characters in the string,
  • Place a marker that indicates the last char of the line, or
  • Keep the pointer to the last char of the string separate from line characters.

C select the second route; other languages ​​(Pascal, etc.) choose the first route. Some C ++ std::string implementations choose the third route * .


* Even std::string implementations that use the first or third approach complete zero buffers for compatibility with parts of the C library. This is necessary to ensure that c_str() returns a valid C string.
+17
source

In C and C ++, c-strings are stored in an array of characters. To allow strings of different lengths, these arrays are often allocated much more than the actual strings they should contain. For example, a programmer can allocate an array of char[256] , which can contain a string from 0 to 255 in length. But the computer must know exactly how long the string actually is, so it must end with a null character. Otherwise, it would be necessary for the length of the character array to be exactly the same as the string (impractical solution, since allocating and copying memory uses a lot of resources).

+2
source

Since the c-style string does not know which character is the last character. For example, if you read the name, you can create a buffer like this:

 char buf[256] // this allows c-style strings that contain 255 characters 

But when you go in to fill this buffer, you cannot (probably will not) use all the space. If you fill it with Jack, the only information you care about is the first five indexes, not all 256.

0
source

Consider each character in a string as blocks of memory in memory. If the string fits in memory. After that, another line is placed next to it, then the computer will consider that the second line is attached to the 1st, if zero is absent. So null acts as a delimiter

0
source

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


All Articles