Converting String input to char array

I want to convert a String to a char pointer(in order to use it as wifi username and password).
I get a weird behaviour in my code and can't figure it out.

bool flag = true;

String username = "user123";
String password = "pass456";

const char* ssid = "";

void setup() {

void loop() {
    if (flag) {
      flag = false;


void convertToCharArray() {
  int unlen = username.length() + 1;
  char charArrayUsername[unlen];
  ssid = charArrayUsername;

Inside convertToCharArray() I get a print of the correct username and in the main loop I get a gibrish. what is the correct way of doing this?

Why are username and password Strings in the first place when they could be declared as C style strings ?

char username[] = "user123";
char password[] = "pass456";

Because the input I get is of String type, I didn't put it in the code to simplify.

  ssid = charArrayUsername;

Both ssid and charArrayUsername are arrays of chars terminated with zeroes to turn them into C style strings. You cannot copy arrays like that, you need to use strcopy()

However, when you do

  username.toCharArray(charArrayUsername, unlen);

then why not put the result directly into the ssid array ? You also need to think carefully about how the username array is terminated

You probably want c_str() c_str() - Arduino Reference

Thanks a lot!
just used this line and it worked:
ssid = username.c_str();

Just as a matter of interest, where are the Strings coming from ?

They come from a BLE characteristic sending the wifi/pass credentials

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.