Using sprintf results in null

Hey there, I’m brand new to this and have never used C/C++ before (jesus, people used to code in this?) and I’m having trouble getting an integer to convert to a string for publishing. I originally tried toString(), which appeared in the particle docs but didn’t work for integers. I have checked through the forums and found sprintf(), but this also doesn’t work; it only outputs nulls, and I can’t work out what I’m doing differently to all the forum posts and examples I can find. Help me to understand what’s going wrong here, please! Here’s an excerpt of my code:

int currentOccupancy = 0;

void setup() {
    Particle.function("Set current occupancy", setCurrentOccupancy);
}

int setCurrentOccupancy(String occupancy) {
    currentOccupancy = occupancy.toInt();
    char* test;
    sprintf(test, "%d", currentOccupancy);
    Particle.publish("Occupancy set:", test, PRIVATE);
    return currentOccupancy;
}

I know that this is a bad example, as I could just publish the occupancy string I’m supplying, and as it is here I’m converting from a string to an int and then back again, but I use sprintf() in other places less easy to isolate for a post here. Just think of this as an example.

I am using the particle console, supplying an int to this function, which sets an int in the code, then needs to publish a message with that int, so the user can see what’s happened. (Again, I know this is a bad example and the return will show the number where I used the function, but just for the sake of example, roll with it).

Why does declaring the char*, setting it with sprintf() and publishing it result in null? What am I missing here? Cheers for your time!

No sooner than I post, do I do some more digging and notice no-one else seems to use char*… Replaced char* with char test[40] and it works fine, and I’m an idiot. Cheers anyway if you read this far…

1 Like

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