views:

105

answers:

5

If I declare a function like this:

string hash (char* key)

then any change I make to key will 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?

A: 

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..

Jack
I think he meant to say "char pointer" instead of "char" in the title.
Vagrant
+2  A: 
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.

pmr
I'll +1, but Jerry I think has the best answer. If you need a copy, might as well let the compiler do it.
GMan
@GMan: Definitely. His answer got even better as soon as I remembered the `Want speed? Pass by value` article on C++Next and the solution is more general.
pmr
+8  A: 

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).

Jerry Coffin
A: 

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.

Igor Zevaka
A: 

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

mathepic