"Invalid conversion from const char* to char*"

Hi all,
this is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

template < typename Var, typename Value >
void Store( Var& var, Value value ) {
    var = value;    
}

int main( int argc, char* argv[] ) {
    char* a;
    Store( a, "Hello!" );
    std::cout << a << std::endl;
    
    std::cin.get();
    
    return 0;
}

Store() assigns the value of the second parameter to the first one.
It gives the following errors (Dev-Cpp):
In function `void Store(Var&, Value) [with Var = char*, Value = const char*]':
10   instantiated from here 
5 invalid conversion from `const char*' to `char*'  

That would mean that the "Hello!" argument is const char* . Is that true? And how do I solve the problem?

(If I do it like this, it works:
1
2
3
char* a;
char* b = "Hello!";  
Store( a, b );
)
closed account (zb0S216C)
String literals are pointers to arrays of constant characters ["char const *"]. Because of this, in your function "Store( )", you're attempting to copy a pointer to constant data ["value"] to a pointer to non-constant data ["a"]. This violates const-correctness, and is therefore not allowed.

That said, your "Store( )" function, once instantiated (type-deduction), becomes this:

1
2
3
4
void Store(char *&var, char const *value)
{
    var = value; // Error; cannot convert from "char *" to "char const *".
}

Fransje wrote:
"If I do it like this, it works:"
1
2
char* a;
char* b = "Hello!"; 

Don't do that. Here, your giving "b" the address of constant data, without respecting the constness of the string literal. Attempting to modify the string in any form will result in a run-time termination.

Wazzak
Last edited on
aha, I see. But what is the right way to do this?
Use:

const char* a = "Hello";
yes, but I want to use the Store() function to assign values.
closed account (zb0S216C)
Well, there's two options:

1) Copy "value" into "var" using "strcpy( )". This isn't exactly safe because "var" may well be pointing to unknown memory; writing to that memory could prove problematic.

2) Use "std::string".

Wazzak
Last edited on
Topic archived. No new replies allowed.