#include <cstring>
char* str0;
const char* str1 = "abc";
// assign str1 to str0
strcpy(str0, str1); // syntax correct, but run time error
str0 = str1; // syntax error, cannot convert const char* to char*
string n_str = str1;
str0 = n_str; // syntax error, cannot convert ...
cout << str0 << endl; // expected output: abc
I'd like to make str0 same as str1 while runtime(after compilation), I don't know how to do it. And for the case str0 = str1; I don't understand why it won't work, because str0 points to nothing, while str1 points to a const string literal, so if I now make str0 point to what str1 is pointing to, it should be fine, but it is not. So it there any way to solve it?
std::string str0;
const std::string str1 = "abc";
// assign str1 to str0
str0 = str1;
cout << str0 << endl; // output: abc
If you insist on using C:
char* str0;
const char* str1 = "abc";
str0 = malloc(strlen(str1) + 1);
// if you use a c++ compiler you need instead:
// str0 = (char*) malloc(strlen(str1) + 1);
strcpy(str0, str1);
// and free after use
// if you use C++ this will not help much
// as pretty much any exception above will cause your code to get out of `free`,
// causing a memory leak
free(str0);
If you insist on using bad C++:
char* str0;
const char* str1 = "abc";
str0 = new char[strlen(str1) + 1];
strcpy(str0, str1);
// and delete after use
// this will not help much
// as pretty much any exception above will cause your code to get out of `delete`,
// causing a memory leak
delete(str0);
Please read about RAII to understand why all of the solutions with manual memory management are bad: cppreference , wiki
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With