neuromancer neuromancer - 4 months ago 12
C++ Question

How to copy a string into a char array in C++ without going over the buffer

I want to copy a string into a char array, and not overrun the buffer.

So if I have a char array of size 5, then I want to copy a maximum of 5 bytes from a string into it.

what's the code to do that?

Answer

First of all, strncpy is almost certainly not what you want. strncpy was designed for a fairly specific purpose. It's in the standard library almost exclusively because it already exists, not because it's generally useful.

Probably the simplest way to do what you want is with something like:

sprintf(buffer, "%.4s", your_string.c_str());

Unlike strncpy, this guarantees that the result will be NUL terminated, but does not fill in extra data in the target if the source is shorter than specified (though the latter isn't a major issue when the target length is 5).