Line length

String manipulation problem

http://www.ideone.com/qyTkL

In the above program (given in the book "C ++ Primer, Third Edition" by Stanley B. Lippman, exercise Jose Lajoy 3.14) the length of the received character is indicated len + 1

char *pc2 = new char[ len + 1]; 

http://www.ideone.com/pGa6c However, in this program the length of the character pointer I was taken len

 char *pc2 = new char[ len ]; 

Why it becomes necessary to take the length of the new line as 1 large when we get the same result. Explain.

Remember that the programs that I showed here are slightly modified. Not exactly the same as in the book.

+4
source share
3 answers

To save a string of length n in C, you need n + 1 char s. This is because a string in C is just an array of char , terminated by the null character \0 . So the memory that stores the string "hello" looks like

 'h' 'e' 'l' 'l' 'o' '\0' 

and consists of 6 char , although the word hello is only 5 letters long.

The inconsistency that you see may be semantic; some would say that the length of the word hello is len = 5, so we need to highlight len+1 char s, while some would say that since hello requires 6 char , we have to say that its length (like string C) len=6 .

Please note, by the way, that the way to store C strings is not the only one possible. For example, you can save a string as an integer (giving the length of the string), followed by characters. (I believe Pascal does this?). If you are not using a length field such as this, you need another way to find out when the line will stop. Method C is that the line stops whenever a null character is reached.

To understand how this works, you can try the following:

 char* string = "hello, world!"; printf("%s\n", string); char* string2 = "hello\0, world!"; printf("%s\n", string2); 

(Purpose char* string = "foo"; is just a shorthand way to create an array with 4 elements and provide the first value of 'f', the second 'o', the third 'o' and the fourth '\ 0 ").

+7
source

This is the convention that a string ends with an extra null character, so anyone who allocates memory should allocate the len + 1 characters.

+1
source

This is causing a problem. But sometimes, when len not aligned, the OS adds a few bytes after it, so the problem is hidden.

0
source

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


All Articles