I am having trouble with sprintf when using it with char...

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

I am having trouble with sprintf when using it with char...

3,210 Views
bob_s
Contributor III
I am having trouble with sprintf when using it with char arrays instead of char pointers even when I use typecasting.

Example:
    char tmpstr[16];

        sprintf((char *)tmpstr, " %X", 1024);

I get a string with %X in it instead of 400.
I'm not a 'C' guru by any stretch.

Any ideas?
Thanks.
Bob
Labels (1)
0 Kudos
4 Replies

420 Views
bob_s
Contributor III
For the record,  by removing the sprintf lines:
    sprintf(tmpstr, "%X",(NVRAM_ADDR + (i * DATA_FLASH_SECTOR_SIZE)));
    sprintf(TxSplrBuf1, "%s %s\r", tmpstr, msg);

from different spots in my code and adding a routines to do the conversions, my problems went away. 

I use sprintf other places in code without problems.  I am running low on FLASH ROM, though I have plenty of RAM.  I don't know it that is part of the problem.

Thanks for the help.



0 Kudos

420 Views
Lundin
Senior Contributor IV
I don't know what is causing your problems, but I do know that sprintf() should be regarded as a hobbyist function only. There are multiple problems with that function: poor execution speed, huge nvm memory consumption, no thread safety, poor standardization of va_arg lists, and so on. As I see it, the only reason it is available is because Codewarrior want to claim ISO C compliance.

Professional embedded programmers will use their own int to string conversion routines.
0 Kudos

420 Views
bob_s
Contributor III
I am running CW 8.1.1a.

I'm sure you are right.  The original line of code was:
sprintf(tmpstr, "%X",(NVRAM_ADDR + (i * DATA_FLASH_SECTOR_SIZE)));
which I was using to report block data for troubleshooting flash erase and writes.

However I use sprintf to combine strings and ints into printable info for serial port echoes.  I'm concerned there will be bugs in other sections of code. 

Do you think I should use alternative routines for all sprintf calls?
0 Kudos

420 Views
CompilerGuru
NXP Employee
NXP Employee
Which processor, which code warrior version are you using?
The code looks fine as far as I can tell.
I saw in this forum that ColdFire is using a specially small version of printf in some case, see the thread referenced below, or search for ColdFire and printf at the bottom of this page.
Daniel

http://forums.freescale.com/freescale/board/message?board.id=CWCFCOMM&message.id=2282


BTW: For "just" converting an int to its hex representation, then probably
a dedicated function for that is much more (code and speed) effective than using printf.
0 Kudos