ashmish2
ashmish2

Reputation: 2967

Strange behaviour of string length function w.r.t null character?

I have this code say:

 std::string str("ashish");  
 str.append("\0\0");  
 printf("%d", str.length());  

It is printing 6 but if I have this code

 std::string str("ashish");  
 str.append("\0\0",2);  
 printf("%d", str.length());  

it is printing 8 ! Why?

Upvotes: 1

Views: 89

Answers (2)

bames53
bames53

Reputation: 88215

It's because str.append("\0\0") uses the null character to determine the end of the string. So "\0\0" is length zero. The other overload, str.append("\0\0",2), just takes the length you give it, so it appends two characters.

From the standard:

  basic_string&
   append(const charT* s, size_type n);

7         Requires: s points to an array of at least n elements of charT.

8         Throws: length_error if size() + n > max_size().

9         Effects: The function replaces the string controlled by *this with a string of length size() + n whose first size() elements are a copy of the original string controlled by *this and whose remaining elements are a copy of the initial n elements of s.

10         Returns: *this.

  basic_string& append(const charT* s);

11         Requires: s points to an array of at least traits::length(s) + 1 elements of charT.

12         Effects: Calls append(s, traits::length(s)).

13         Returns: *this.

                                                               — [string::append] 21.4.6.2 p7-13

Upvotes: 4

Luchian Grigore
Luchian Grigore

Reputation: 258618

From the docs:

string& append ( const char * s, size_t n );

Appends a copy of the string formed by the first n characters in the array of characters pointed by s.

string& append ( const char * s );

Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).

The second version (your first one) takes into account the null-terminator (which in your case is exactly the first character). The first one doesn't.

Upvotes: 3

Related Questions