Avatar ·

How to convert std::string to char* in C++? Problems with c_str() and data()

Hello everyone! I just started learning C++ and encountered a problem. I need to pass the contents of std::string to a function that only accepts char* (not const char*). I know that std::string has c_str() and data() methods, but they return const char*, and the compiler complains that I cannot pass const to a non-const parameter. I tried doing this:\n\n```cpp\nstd::string myStr = "Hello, world!";\nchar* ptr = myStr.c_str(); // Error: cannot convert const char* to char*\nsomeFunction(ptr);\n```\n\nThen I read that you can use const_cast, but it looks dangerous. I also saw someone copying the string into a char array using strcpy. Which of these is correct? Or is there a standard way to get exactly char* (not const) from std::string? Thanks in advance for your help!