Alex Rivera | Logout

String going crazy if I don't give it a little extra room. Can anyone explain what is happening here?

Asked 2011-05-04T11:41:39.733
36

First, I'd like to say that I'm new to C / C++, I'm originally a PHP developer so I am bred to abuse variables any way I like 'em.

C is a strict country, compilers don't like me here very much, I am used to breaking the rules to get things done.

Anyway, this is my simple piece of code:

char IP[15] = "192.168.2.1";
char separator[2] = "||";   

puts( separator );

Output:

||192.168.2.1

But if I change the definition of separator to:

char separator[3] = "||";

I get the desired output:

||

So why did I need to give the man extra space, so he doesn't sleep with the man before him?

Edit
Report

2 Answers

22

Strings in C are NUL-terminated. This means that a string of two characters requires three bytes (two for the characters and the third for the zero byte that denotes the end of the string).

In your example it is possible to omit the size of the array and the compiler will allocate the correct amount of storage:

char IP[] = "192.168.2.1";
char separator[] = "||";

Lastly, if you are coding in C++ rather than C, you're better off using std::string.

answered 2011-05-04T11:44:25.657
13

If you're using C++ anyway, I'd recommend using the std::string class instead of C strings - much easier and less error-prone IMHO, especially for people with a scripting language background.

answered 2011-05-04T11:48:12.687

Your Answer