Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of String

Tags:

c++

c

String manipulation problem

http://www.ideone.com/qyTkL

In the above program (given in the book C++ Primer, Third Edition By Stanley B. Lippman, Josée Lajoie Exercise 3.14) the length of the Character pointer taken is len+1

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

http://www.ideone.com/pGa6c However, in this program the length of the Character pointer i have taken is len

char *pc2 = new char[ len ];

Why is there the need to take the length of new string as 1 greater when we get the same result. Please Explain.

Mind it the Programs i have shown here are altered slightly. Not exactly the same one as in the book.

like image 878
Sadique Avatar asked Feb 24 '23 23:02

Sadique


1 Answers

To store a string of length n in C, you need n+1 chars. This is because a string in C is simply an array of chars terminated by the null character \0. Thus, the memory that stores the string "hello" looks like

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

and consists of 6 chars even though the word hello is only 5 letters long.

The inconsistency you're seeing could be a semantic one; some would say that length of the word hello is len = 5, so we need to allocate len+1 chars, while some would say that since hello requires 6 chars we should say its length (as a C string) is len=6.

Note, by the way, that the C way of storing strings is not the only possible one. For example, one could store a string as an integer (giving the string's length) followed by characters. (I believe this is what Pascal does?). If one doesn't use a length field such as this, one needs another way to know when the string stops. The C way is that the string stops whenever a null character is reached.

To get a feel for how this works, you might want to try the following:

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

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

like image 56
gspr Avatar answered Mar 06 '23 22:03

gspr