How to make a copy of a char and not a reference in C++
If I declare a function like this:
string hash (char* key)
then any change I make to key wil开发者_StackOverflow社区l also change it's value when the function exits, correct?
I want to make a copy of it in the function so that I can safely change it without changing the original value.
I tried this, but it doesn't work.
char temp = key;
How can it be done?
Probably the most obvious would be to change your parameter to a string:
std::string hash(std::string key) {
// ...
}
In a typical case, you'd want this to be a std::string const &
, but in this case you want a modifiable copy of the original, so you pass the string by value. Since a string can be (implicitly) constructed from a char *
, you can still pass pointers to char to it without a problem (and the compiler will construct a string automatically where needed).
std::string tmp(key);
tmp will be initialized to a copy of key. Make sure that key is null-terminated otherwise this will end in tears. See this for a overview of std::string
ctors.
Declare the function as std::string hash(const char* key);
this will make it obvious that key will not change and protects you from changing it by accident.
just use
string hash(char key)
this will push the char onto the stack and just its local version will be used within the scope of the function.
Oh, reading it again maybe you want to copy a string instead that a single char, in this case you can use strdup
but don't forget to relese its memory at the end of the function. Finally you can also use the copy constructor of string
class if you are planning to convert it to a std::string
anyway..
I think your syntax for copying a char array into std::string
is a bit wrong. To make a copy of a string just do this:
std::string copy(key);
On seconds thought, std::string = (char*)something
should have worked, as string defines an assignment operator.
Use strcpy
if you want to keep the parameter as a char pointer.
The definition:
char *strcpy(char *destination, const char *source);
You also use strdup
char temp = *key;
I believe.
精彩评论