Particle.publish string vs snprintf %s

A bit rusty on C/C++ I don’t understand why %s does not provide the expected result here (OS 1.5.2):

int ITV = 5;
String MAC = "c1:c2:c3:c4:c5:c6";

void setup() {
	char buf[60]; 
	snprintf(buf, sizeof(buf), "{\"R\": %s ,\"I\":%i,\"D\":\"{3720:-11.7, 3800:10.4}\"}", MAC, ITV);
	Particle.publish("HLP1log", buf, PRIVATE);
	Particle.publish("HLP1log", MAC, PRIVATE);

void loop() {


Results in the Console:

{"R": ��  ,"I":5,"D":"{3720:-11.7, 3800:10.4}"}

I would expect %s to get the MAC string included in the first result?

Not looked at it very closely, but one red flag is String MAC.

String objects are no C-strings but snprintf() needs one where a %s is expected.

You can either use (const char*)MAC or MAC.c_str() to “derive” a C-string from a String object.

When directly referencing MAC you are actually handing over the object pointer and snprintf() expects to find the start of the %s string there.
But since this is only the base address of the object’s dynamic data area you will not find the internal string buffer but some other object fields stored before the string buffer.


Ah, yes, the lovely “Arduino strings”. (const char*)MAC does the job, Thanks!

1 Like

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