I’m trying to create a function that will right justify some integer data. And pad the front of the data to fill the specified field width.
If passed field = 5 and data =34 it should return
sss34 Where s are spaces.
My code works when its inline and not in a function.
As a function I get compile warnings and the code will not run.
D:\Arduino_ReferenceCode\memmove\RtJustify\RtJustify.h: In function 'char* RightJustify(uint8_t, uint8_t)':
D:\Arduino_ReferenceCode\memmove\RtJustify\RtJustify.h:47:10: warning: address of local variable 'destinationField' returned [-Wreturn-local-addr]
char destinationField[] = {0x2D,0x2D,0x2D,0x2D,0x2D,0x2D,0x2D,0x2D,0x2D,0x2D}; //{0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20};
I’m not great when using pointers however it seems I would have to do one of these:
- malloc for the array “destinationField”
- Create “destinationField” as a static.
- or could I just make “destinationField” a global?
Any guidance would be appreciated
Thanks
John
In the below, destinationField is filled with spaces (I’ve used dashes for debugging). More spaces than I need, then I terminate the array with \0 for the length of the printing field.
I then insert my data into this array at a position that ends up being right justified.
The array spaces insures I clear the field when going from say 143 to 95
char* RightJustify(uint8_t field, uint8_t data)
{
char buffer[10]; // longer than we expect any value to be
char destinationField[] = {0x2D,0x2D,0x2D,0x2D,0x2D,0x2D,0x2D,0x2D,0x2D,0x2D};
destinationField[field] = '\0'; // truncate the destination field to the length of the field
itoa(VOCvalue, buffer, 10);
uint8_t valueLen = strlen(buffer);
memmove (destinationField + (field - valueLen), buffer, valueLen);
return destinationField;
}