Char Array String not Saving when it's Being Overwritten

Hi all

I’m very new to all this and am having trouble with string arrays.

I’m using Ping() to determine the distance of an object. Based on that distance, i want to select a certain SMS content and send that message out.

I’m using the standard example code for sending an SMS and for the distance sensor and modifying it. The array is initialised before setup(). See below

char txtMsg[50]="1st text message";

In Loop() I want to set txtMsg[50] to be “Greater than 10 feet” if the distance was > 10 feet or “Less than 10 feet” if the distance was < 10 feet etc etc.

I’m doing it this way:

if (distance >= 10 && distance < 15) { char txtMsg[50] = ("Distance is between 10 and 15%"); }

I do a serial.print to see the value of the variable and it’s the new value as expected

I’m then sending the SMS at the end of the code (still within Loop() ):

 // sms.beginSMS(remoteNumber);
 sms.print(txtMsg);
 sms.endSMS();

BUT the SMS i receive is the original value (“1st text message”) when the variable was first initialised.

What am i missing / doing wrong ? Is it something to do with memory allocation ? Do i have to commit it or something ?

As i said, this is all very new to me and i apologise if this is a silly question. I’ve been through the reference guides and this forum, but i can’t see anything relevant.

Many thanks

BB

You dont appear to be using the same array. You are actually making a new array here.

if (distance >= 10 && distance < 15) { char txtMsg[50] = (“Distance is between 10 and 15%”); }

just have txtMsg = “Distance is between 10 and 15%”;

Post your full code and please use code tags, look for the <> above this face :neutral_face:

HazardsMind: txtMsg = "Distance is between 10 and 15%";

That won't work since txtMsg is a character array, not a String object. You could use:

strcpy(txtMsg, "Distance is between 10 and 15%");

Or you could use character pointers:

char *txtMsg = "1st text message";
.
.
.
txtMsg = "A different text message";

That won't work since txtMsg is a character array, not a String object.

Good catch. Its a constant going into a non constant, which doesn't work.

strcpy() is the way to go.

Thanks for the help guys, it works perfectly now.

Point taken re posting all the code. I wasn't sure if i posted the code correctly, hence only posting a couple of lines.

Thanks again

BB