Question

just wondering if this is possible,

I would like a string input equal to a char, when the input button is pressed.

so at the top i define WLAN_SSID

#define WLAN_SSID       "abc"

I have also initialized the input which changes depending on the buttons pressed on the device.

String input = "abcdefg";

and somewhere below in the code I have :

char *ssid = WLAN_SSID;  

I need *ssid to stay as char, but is there anyway to make it equal to the String 'input'?

thanks

Was it helpful?

Solution

You certainly can not assign WLAN_SSID to a char* because string literals are of type char const[N] (with a suitable N) which happily decay into char const*s but refuse to be assigned to char*s. If you really need to deal with a char*, you'll need to allocate sufficient space and copy the value into this memory. Of course, when changing it you'll also need to release the memory appropriately. For example

char* make_ssid(char const* value) {
    static std::unique_ptr<char[]> memory;
    std::size_t n = strlen(value);
    memory.reset(new char[n + 1]);
    strncpy(memory.get(), value, n + 1);
    return memory.get();
}
char* ssid = make_ssid(WLAN_SSID);

OTHER TIPS

First you need to allocate space for the char[].

ssid = malloc(sizeof(char) * (input.length() + 1));

Then you need to use String::toCharArray() to copy the characters into the buffer.

input.toCharArray(ssid, input.length());

And then later, when you're done with ssid, you need to discard the memory you allocated for it.

free(ssid);

You may also need to discard the original value of ssid before reusing it, but I don't know enough about Arduino to be sure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top