There are many problems with your code.
Your function is declared as returning a single char
, not an array of char
s. And it is missing an actual return
statement. But even if it weren't, you would be returning a local array that goes out of scope when the function exits, leaving the caller with a dangling pointer to invalid data.
You are declaring the opChar
array in a non-standard way known as a "variable-length array". VLAs are a compiler-specific extension, and thus not portable. You need to dynamically allocate the array using new[]
instead.
Try this:
char* string2char(const String &ipString){
char *opChar = new char[ipString.length() + 1];
/*
for (int i = 0; i < ipString.length(); i++)
opChar[i] = ipString.charAt(i);
*/
ipString.toCharArray(opChar, ipString.length());
opChar[ipString.length()] = '\0';
return opChar;
}
char *charssId = string2char(AP_NameString);
// use charssId as needed...
delete[] charssId;
A safer option is to use std::string
instead:
std::string string2char(const String &ipString){
std::string opChar;
opChar.resize(ipString.length());
/*
for (int i = 0; i < ipString.length(); i++)
opChar[i] = ipString.charAt(i);
*/
ipString.toCharArray(opChar, ipString.length());
return opChar;
// alternatively:
// return std::string(ipString.c_str(), ipString.length());
}
std::string charssId = string2char(AP_NameString);
// use charssId.c_str() as needed...
But a conversion is actually not needed at all:
const char *charssId = AP_NameString.c_str();
// use charssId as needed...