char array questions [solved]

Question1: If you have some variables like:

byte keys = 7;
char myString[10] = "-3.141";

What is the preferred way to add the value of "keys" at the end of "myString", so that "myString" becomes (in this case) "-3.1417" ?

Question2: Is there a command that will assign a new string to a char array ? When using String class there is the assignment operator but how do you do it with a char array ? Do I need to assign every element individually one by one ?

Question3: Is there a command to add/remove the first or last char in an char array ?

Take a look at strcat strcpy and strlen.

...and remember that you need to convert keys to ASCII

int len = strlen(myString);
if (len < 9) {
    myString[len++] = keys + '0';  // Convert one digit (0-9) to ASCII
    myString[len] = '\0';  // NULL terminator
}

How is strcpy supposed to work ? If I have

char myString[10] = "seven";

strcpy(myString, "two");

Do I get "two" or "twoen", in other words does it take care of the nul termination sign at the end ?

When I use

strcat("-", myString);

I get

warning: deprecated conversion from string to "char*" [-Write-strings]

Why do I get this warning ?

just read about strcpy()

cinnamonBunny:
How is strcpy supposed to work? If I have

char myString[10] = "seven";

strcpy(myString, “two”);



Do I get "two" or "twoen", in other words does it take care of the nul termination sign at the end ?

You get “two”. It copies the null terminator along with the string.

cinnamonBunny:
When I use

strcat("-", myString);

I get

warning: deprecated conversion from string to "char*" [-Write-strings]

Why do I get this warning ?

You are trying to copy an array of characters into a string constant. This will likely cause a crash, especially if your character array contains a string of more than one character.

In general you should be using “strncpy(destination, source, destination size)”.

char myString[10] = "seven";
strncpy(myString, "two", 10);

If you don’t, then someone could enter a string larger than you expect and cause memory corruption. This is a common way that programs develop security vulnerabilities.

Many of the string processing functions involve a "source" of the data and a "destination" where to put the data. So something like strcpy() has:

  • strcpy(destination, source);*

In every case, destination must be a char array which acts like bucket into which you pour the characters that are being held in source. Your code:

  • strcat("-", myString);*

is trying to dump the characters in myString[] into a destination that is a single character. That will never work since there's really no place to put the characters.

Do I get "two" or "twoen"

It would have taken less time to try it and see than to post this question.

Thank you for the people who tried to help.