Reputation: 1
As part of a small program i need to convert a string to a char array. I want to use the strncpy_s() method but I keep getting an assertation saying that the "buffer is too small". This is what my code looks like:
char* ostr = new char[sizeof(str)+1];
strncpy_s(ostr, sizeof(ostr), str.c_str(), sizeof(ostr));
Hope someone can help me.
Upvotes: 0
Views: 252
Reputation: 409196
The variable str
is, it seems, a std::string
object. The size of the object is the size of its member variables, which for std::string
commonly is a pointer (to the actual string) and variable for the length of the string.
If you want to get the length of the wrapped string you need to use the length
function.
Furthermore, there is another problem with your call to strncpy_s
: You do sizeof(ostr)
, which is the size of the pointer, not the size of the memory it points to.
Lastly, if you want to pass a pointer to the string to a C function, then either use str.c_str()
directly in the call. Or if the C function needs to modify the string (but not reallocate it) then use e.g. str.data()
or &str[0]
.
If the C function needs to reallocate the data then you can't use new[]
to allocate it. You need to use malloc
(or possibly strdup
if your system have it).
Upvotes: 3