1

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.

2
  • What are you trying to achieve with that? Commented Oct 20, 2010 at 8:25
  • 1
    I'm sorry, but this is way to vague to answer. (Why would filling be terminated early depending on something read in the array to fill?) You might want to improve that question. For now I voted to close it. Commented Oct 20, 2010 at 8:31

2 Answers 2

5

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

?

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.