Trouble understanding how to use Char * variable

Hi All,

I have code that will compile and run, but has a bunch of warnings about some variables I use.

I declare a variable before setup, and then during the setup routine, I use the particle ID to get site specific details. I'll use one here which is an API key - the API key gets the particular site data to the right graph so we understand where it came from.

I declare a variable:

char * myWriteAPIKey;

Then I put the data into the variable:

if (myID.equals("e00fce68370b9dd38b709203")) {
myWriteAPIKey = "APIKEYGOESHERE";
}

but I get the following problem during compile:

warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

how do I get the char* or string formatted properly?

That will happen, and there are two common fixes:

const char *

You can change the global variable declaration to:

const char * myWriteAPIKey;

The reason for this is that with a const char * you can change the pointer, but you can't change the contents of the things that are pointed to. So you can assign it to a different string, but you couldn't change only the first character of the string, for example.

This is important because the string in myWriteAPIKey = "APIKEYGOESHERE"is a const string. The string is stored in flash memory with the code and can't be modified at runtime, so you can't assign it to a char * variable because that means the string to be modified, and it can't be modified.

String

The other common solution is to declare it like this:

String myWriteAPIKey;

The main difference is that when you do the assignment, you are making a copy of the string. So the const string "APIKEYGOESHERE" still exists in flash memory in the code, but when you assign it, a copy is made to myWriteAPIKey on the heap. That allows it to be modified later, if desired.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.