|ARM Technical Support Knowledge Articles|
Applies to: C51 C Compiler
Information in this article applies to:
In C51, I am using printf and sprintf with many arguments and it is printing out wrong values. What is the reason for this behavior?
There are any number of reasons why printf can output incorrect values.
Probably the most common reason is that the format specifier and the argument type do not match. To solve this kind of problem, explicitly type cast each argument to the desired type. Be sure that you accurately specify the correct format specifier for that type.
Another reason may be that the number of bytes you may pass to functions with variable-length argument lists is fixed (since arguments are not passed on the stack). In small and compact memory model, printf and sprintf only reserve 15 bytes for the argument list. In the large memory model 40 bytes are reserved. For example, 15 bytes allow you to pass up to five generic (3-byte) pointers, or one generic pointer and three long arguments. This parameter limitation is a compromise to the limited memory available in 8051 devices.
Eight arguments will not fit in the space reserved for small or compact memory models. So, instead of one sprintf call with many arguments you must perform two or three calls and distribute the arguments among the sprintf calls. For example:
The following code exceeds the parameter space limits since seven generic pointers (21 bytes) are passed to sprintf.
char str = "Any Text"; sprintf (buff_out, "%s %s %s %s %s", str, str, str, str, str);
The above example may be rewritten as follows:
char str = "Any Text"; int len; len = sprintf (buff_out, "%s %s %s ", str, str, str); sprintf (buff_out + len, "%s %s", str, str);
Article last edited on: 2005-07-15 10:15:51
Did you find this article helpful? Yes No
How can we improve this article?