I need to pass a string variable into a function that changes it and sets a flag high so that it enters an if statement the next time through the loop that updates an HMI.
The applicable portion of the code are as follows:
char machineStatus[] = "";
// using the function
writeString(machineStatus, "idle");
// the non working function
void writeString(char *stringName, char *newString){
stringName = newString;
updateStrings = 1;
}
This complies and goes onto the arduino with no issues however the machineStatus doesn't get updated, only a new string called stringName is made and updated as "idle" in this case. I don't want a new new string, I just want the machineStatus string to change to "idle" in this case.
Creating a C-string as an array has the advantage of being able to get the sizeof that array. You don't specify the size between the square brackets; the compiler can compute it based on the bytes in the resulting string, plus the terminating NUL character. So this is one byte.
However, since you are assigning other strings to this one, it is misleading in this case. Instead, you should use a plain pointer
const char *machineStatus = "";
And since the intent is not to modify the content of any of these strings, it is const; which is what any literal C-string is. The pointer points to a reasonable default value -- an empty string. Then in your function, in order to modify this pointer, you pass a reference to it
This solution will not work if you call updateString from another function...
After leaving that other function the pointer will point where the local string used to be...
The strncopy() solution is definitely better.
then localPtr is on the stack, but its value points towards some permanent memory (usually in non writeable memory for 32 bits architectures usually flash, on AVR it will be in RAM) so the pointer itself has a life time of the program
so not sure about that. It depends if you want to work with mutable buffers as well. If not, you use more memory than really necessary and create a dependancy on your buffer size meaning some copy could get truncated.
I am very novice at this but trying to learn rapidly now and I can't thank you enough for sharing your knowledge! Sorry for the late reply I got pulled onto another project that finally ended yesterday and I'm back to learning coding for our new machine so I came back to this and your answer is SO helpful! Thanks again!