I am trying to copy a string which might contain null characters in the middle to a char array.
I have constructed the following function.
void SaveStringToChar(string &mystring,const char * &ArrChar)
{//begin function
std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0';
ArrChar = writable;
}//end function
my question is this method guarantees that I wont lose the characters after a null element.
and my other question is I get this linker error which I don’t know what it means.
/tmp/ccUpCRaz.o: In function `Parser::RuleParser(char const*)’:
Parser.cpp:(.text+0x3f6): undefined reference to Parser::SaveStringToChar(std::basic_string, std::allocator >&, char const*&)’
collect2: ld returned 1 exit status
anyhint please.
this is the function I pass things to compare.
void Search( size_t TextLength, const char *Text, const vector<const char *> &patterns );
You need to define the function as a member of
Parser::. It is currently defined as:Change to:
The
std::copy()will copy all the characters. However, the caller will not know how many charactersArrCharactually points to as functions likestrlen()will stop counting at the first null character. You could change the signature ofSaveStringToChar()to accept another argumentsize_t& ArrCharLenthat would be populated with the number of characters inArrChar. Of course,mystringwill have the length ofArrCharso maybe you are already storing this prior to the call toSaveStringToChar().EDIT (after
vector<const char*>comment):The true number of bytes is lost once the
const char*is added to thevector. Why not use avector<std::string>and you havestd::string::length()to know how many characters there are actually stored instd::string.EDIT2 (after comparison function .c_str() with text.length():
Instead of passing
.c_str()and.length()to compare against elements in avector<const char*>just pass thestd::stringto the compare function and compare against elements of avector<std::string>: thestd::string::operator==()will correctly compare strings will embedded null characters. You could then usestd::find()to search thevector<std::string>for thestd::stringread from the file.