and using this function i need to set a member variable which is a char* m_buf. c++ didn't like a plain = on them ("a value of type "const char *" cannot be assigned to an entity of type "char *"")
i don't know any other way to set it, though, everything that i've googled leads to a solution that is either unrelated to my problem or just can't be incorporated. is there a "non-const cast"? (note: i can't change the function signature, and i can't change the type of that member variable, since it must be non-const)
const_cast ?
in c++ char* is deprecated because it has an undefined behavior eg: char* text = "text"; text[0] = 'a'; // undefined behavior you could use this if you just can't use anything else std::string s = "text"; char* c_text = const_cast<char*>(s.c_str()); std::cout << c_text << '\n';
Show function signature, variable definition and how you call the function.
void set( const char* buf, int size ) this function is a member of a Coder class inside that class: private: char* m_buf; // i can change this but this must not be a const variab;e! example of a function call: Coder coder; coder.set(buf_hello, size); buf_hello is a const char* cstring literal and i can't change it in any way (neither can i change how the function is called)
Change the function itself so that it copies data (not the pointer!) from the argument.
oo great idea, thanks!
hi, i tried using std::copy like this std::copy(buf, buf + size, m_buf); but it results in a segmentation fault. i've never used copy before so i'm not sure what i'm doing wrong, buf points to the first character and buf + size points to the null terminator, so it should copy the data in that range to m_buf, right?
Did you allocate the momory for the copy?
m_buf is initialized, is there anythinп else i should do? in the examples i've seen for std::copy there weren't any mallocs or similar things..
Initialized to what??
std::copy has a bug in libstdc++ in some old versions of gcc
I think you should use memcpy
Обсуждают сегодня