I'm just studying C and C++ programming.
I've searched and can't seem to find an answer that has a decent response. Of course using <string>
is much easier but for this task I am REQUIRED to use only clib <string.h>
functions; I'm also not allowed to use C++11 functions.
I have the 2 variables below, and want to move the contents of buffer
into c
.
vector<char> buffer;
char* c = "";
How can I do this easily?
I have this so far but it obviously doesn't work, otherwise I wouldn't be here.
for (int b = 0; b < buffer.size(); b++)
{
c += &buffer[b];
}
The simplest way I can think of is;
std::copy()
is available in the standard header<algorithm>
.This assumes the code that places data into
buffer
explicitly takes care of inserting any trailing characters with value zero ('\0'
) into the buffer. Without that, subsequent usage ofc
cannot assume the presence of the'\0'
terminator.If you want to ensure a trailing
'\0'
is present inc
even ifbuffer
does not contain one, then one approach is;One could also be sneaky and use another vector;
As long as the code that uses
c
does not do anything that will resizev
, the usage ofc
in this case is exactly equivalent to the preceding examples. This has an advantage thatv
will be released when it passes out of scope (no need to remember todelete
anything) but a potential disadvantage thatc
cannot be used after that point (since it will be a dangling pointer).