tags:

views:

64

answers:

2

NoobQuestion: I heard that filling a char array can be terminated early with the null char. How is this done? I've searched every single google result out there but still have come up empty handed.

+5  A: 

Do you mean something like this:

    char test[11] = "helloworld";
std::cout << test << std::endl;
test[2] = 0;
std::cout << test;

This outputs

helloworld
he

?

Philipp
+1, @user481407: also note that the size is the size of helloworld+1 because of null-terminated string.
Green Code
+1  A: 

That's a convention called "null-terminated string". If you have a block of memory which you treat as a char buffer and there's a null character within that buffer then the null-terminated string is whatever is contained starting with the beginning of the buffer and up to and including the null character.

const int bufferLength = 256;
char buffer[bufferLength] = "somestring"; //10 character plus a null character put by the compiler - total 11 characters

here the compiler will place a null character after the "somestring" (it does so even if you don't ask to). So even though the buffer is of length 256 all the functions that work with null-terminated strings (like strlen()) will not read beyond the null character at position 10.

That is the "early termination" - whatever data is in the buffer beyond the null character it is ignored by any code designed to work with null-terminated strings. The last part is important - code could easily ignore the null character and then no "termination" would happen on null character.

sharptooth