dtostrf not givving desired result

This little skech gives me headache:

char     xStrBuffer[7]   = "";
char     yStrBuffer[7]   = "";

float    newXAxis          =  0L;   // Holds the new value where the dish should point to
float    newYAxis          =  0L;

void setup() {
  Serial.begin(115200);                    // Start the Serial communication

      dtostrf(newXAxis,7, 2, xStrBuffer);    // Create the  x value to print
      dtostrf(newYAxis,7, 2, yStrBuffer);    // Create the y value to print

      Serial << xStrBuffer << endl;     // Print only the x value
      Serial << xStrBuffer <<  " -" << yStrBuffer << endl;     // Print both x and y values

void loop() {

The result of first print looks like : 123.45 89.99
And the second print looks like : 123.45 89.99 - 89.99

Did i mis something here? And if so what.


I don't understand why you're seeing those values, because your sketch only uses zeroes, but the reason the serial print is producing unexpected output is probably that your buffers are too small. You're specifying the minimum width as 7 chars, but your buffer is only 7 chars long so you don't have space for the null terminator. I suspect you'll find the terminator is actually ending up in memory occupied by the second buffer and is being clobbered when you use the second buffer. Make your buffers long enough to hold the strings you're creating, and that should take care of it.

This little skech gives me headache:

You are lying to the dtostrf() function. You do NOT have room for 7 characters plus a terminating NULL in the array. You MUST accept the fact that you need a larger array.

O stupid me, your correct. The values should have been 123.45 and 89.99. It now works after some extra adapting e.g.:

char     xStrBuffer[8]     = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
char     yStrBuffer[8]     = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};

So i know that the last character is always zero