Reputation: 5796
I've already gone through the following links but couldn't get it to work:
Adding to c* invalid conversion from const char* to char*"
Why is conversion from string constant to 'char*' valid in C but invalid in C++
I'm working on arduino Uno. I need to send an argument of type char*
to a function. I have the following code:
const char* topic = "SampleTopic";
const char* msg = "Hello";
publish(0, 0, 0, "msgid", topic, msg);
I'm getting this error:
initializing argument 5 of 'void GSM_MQTT::publish(char, char, char, unsigned int, char*, char*)'
void publish(char DUP, char Qos, char RETAIN, unsigned int MessageID, char *Topic, char *Message);
warning: invalid conversion from 'const char*' to 'char*' [-fpermissive]
publish(0, 0, 0, _generateMessageID(), topic, msg);
^
I've even tried using const std::string& topic = "SampleTopic";
but get this error:
'string' in namespace 'std' does not name a type
Even const char* topic = (char*)"SampleTopic";
and passing it as func(topic)
gives the same error.
How can I resolve this ??
Upvotes: 1
Views: 3340
Reputation: 16785
I don't known anything about the GSM_MQTT::publish()
function but if it requires some modifiable strings (char *
without const
) for Topic
and Message
, then you have to provide modifiable strings.
char topic[] = "SampleTopic";
char msg[] = "Hello";
(you have to make sure the storage is sufficient for the modifications)
On the other hand, if this function does not actually require some modifiable strings, then it is probably a mistake in the API and these parameters should have been declared const char *
.
If this is actually the case, you can safely use const_cast
(or even a traditional C cast) when passing your two const char *
arguments.
const char* topic = "SampleTopic";
const char* msg = "Hello";
publish(0, 0, 0, ???msgid???, const_cast<char *>(topic), const_cast<char *>(msg));
Note that in your example you use the string "msgid"
where an unsigned int
is expected.
Upvotes: 1