Is there any way to write a cstring literal (or variable) directly into an existing std::array?
I.e., I want to do something like this:
std::array<unsigned char, 100> test;
// std::copy("testing", test);
// test="testing";
I expect the behavior to be “copy until either a null terminator is copied or the destination buffer is full.”
I was trying to avoid doing a strlcpy(test.data()… because I was looking for a way that could cope with a buffer overrun without having to explicitly include the buffer length as a parameter.
Thanks.
edit:
Here’re the best solutions I’ve found so far from suggestions. This one only works for literals. MSVC does not have uniform initialization, so it requires the = before then {. It also requires the buffer size, but fails compilation if the buffers sizes don’t match or if there is an overrun:
#include <array>
#include <algorithm>
#include <iostream>
int main() {
std::array<char, 100> arr1={"testing"};
std::array<char, 100> arr2;
arr2=arr1;
std::cout << arr2.data();
}
This one works for strings in general, but be careful because the embedded null does not get copied and to have the null included you have to construct by array, ie string mystring(“junk\0”, 5).
#include <string>
#include <array>
#include <algorithm>
#include <iostream>
int main()
{
const std::string str("testing");
std::array<char, 100> arr;
std::copy(str.begin(), str.end(), arr.begin());
// Note that the null terminator does not get copied.
}
This should do it:
If you use a too-large string literal, the
std::arrayconstruction will fail on compile time. This won’t work for non-literals though.For non-literals, you need to check for the null terminator yourself. You could do something like
std::copy(my_non_literal, my_non_literal + length_literal, test.begin());, but I think you’ve already come across that one.