Trying to read the elements of a *char array

Hi, new to the Particle platform. I am working with a piece of code that I found online and I am trying to read the elements of the following

char *conditions[] = {
    "clear-day", "clear-night", "rain", "snow", "sleet", "wind", "fog", "cloudy", "partly-cloudy-day", "partly-cloudy-night"
};

If I use the following

Serial.printlnf("testing %d", String(conditions[9]));

or change the index to 5

I only see testing 536883016, in both of the cases.

Any ideas as to what I am doing wrong.

%d means to interpret the variable as a decimal value. For C strings use %s instead.

1 Like

In addition to that you don’t what to wrap the C-string in a String object.

Thank you so much! That solved the conversion problem. However, I am still curious to know why the same value was displayed even though the index was changed.

Can you please elaborate on that? I am still learning C and C++.

You'd just write this

  Serial.printlnf("testing %s", conditions[9]);

Wrapping it in String(....) creates a temporary String object, copies the original string into that object and then provides the pointer to the temporary String object (which is not the pointer to the buffer that now contains the copy tho') to the string formatting routine (e.g. sprintf()).
Hence you don't want to do that.

That's also the answer to that question - you are dealing with the pointer to your temporary String object which will be created in the same spot on the stack over and over again (although the internal string buffer will often not be as it's dynamically allocated on the heap).

BTW, since you are not intending to change your strings nor the pointers to those strings you should consider declaring them as const char* const conditions[] (an array of immutable pointers to non-changable strings).

Thanks @ScruffR I overlooked that part.

1 Like