Trouble setting value of const char* variable

Here’s stripped down code of what I’m working with.

const char* on = "false";
float setTemp = 0.00;

void setup(void) {
  Particle.function("setData", setData);

void loop(void) {
  char tmpData[64];
  sprintf(tmpData, "{ \"setTemp\": %2.2f, \"on\": %s }", setTemp, on);
  Particle.publish("getData", tmpData);

int setData(String command) {
  int loc1 = 0;
  loc1 = command.indexOf(",");
  setTemp = command.substring(0,loc1).toFloat();
  on = command.substring(loc1+1).c_str();

  return 1;

When I call setData() from the CLI with:

$ particle call PHOTONIDHERE setData "67.25,true"

And then listen to my getData event with:

$ particle subscribe getData PHOTONIDHERE

The value of ‘on’ gets set to ‘P_’ instead of true. But I’ve also seen it set to ‘U’ and ‘t_’:

{"name":"getData","data":"{ \"setTemp\": 67.25, \"on\": P_ }","ttl":"60","published_at":"2015-10-26T14:00:38.795Z","coreid":"..."}

Admittedly, I’m new to C++… Any help is much appreciated!

Hi @danof

The const keyword means constant, as in not changeable, and on Particle devices the storage for const arrays/strings is allocated in Flash memory that is not writeable except to load a new program.

You need to:

  • Remove the const keyword from the declaration of on like this char on[] = "false";
  • Use strcpy(on,command.substring(loc1+1).c_str()); to copy the contents of the command string into your global on char array.

I agree with bko, but with the following difference: declare the on array with a fixed, specific size and then use strncpy() to avoid a buffer overflow.


Hi @Muskie

You are right that I was assuming the only legal values would be “true” and “false” and since “false” is longer than true, it should be safe, but it is best to be explicit.

Thanks bko and Muskie. That worked great!

1 Like