PROBLEMS WITH SPRINTF

Hi

i am having a problem with the sprintf function. i don't know what i am doing wrong.

i created a function where i use sprintf to separate the digits of a decimal number, and the first time that i called the function it works fine. The second time the sprintf starts when the first time left, and so on.

The variable looks something like this the first time: "0123"

and the second time: "0123123"

I don't know if i have to reset a pointer (or how to do it) so everytime i call the function it starts at the beginning of the array.



the code looks something like that:

void send_code (void)
{
int n;
	if (oper_code < 1000){
	n = sprintf (code_char, "%d", 0);
        }
	n += sprintf (code_char+n, "%d", oper_code);
  .
  .
  .
}



void main (void)
{
  .
  .
  .
while (1)
  {
  send_code();
  }
}
.

thanks in advance

Parents
  • You're talking in riddles. For anybody to offer meaningful help, you absolutely have to show a reproducible test case: i.e. actual, complete source code of an example that exhibits the problem, any non-default compiler options you use, plus any input you feed it, the exact results, and possibly how you extracted those results from the running program.

    For starters: you said later that 'n' was initialized --- well, in the source you show it rather clearly is not (or rather: only half the time). You also said

    The variable looks something like this the first time: "0123"

    and the second time: "0123123"


    If so, you must have caused undefined behaviour, since code_char is only 5 characters long, so there's absolutely no way it could ever hold an 8-byte string like the above.

Reply
  • You're talking in riddles. For anybody to offer meaningful help, you absolutely have to show a reproducible test case: i.e. actual, complete source code of an example that exhibits the problem, any non-default compiler options you use, plus any input you feed it, the exact results, and possibly how you extracted those results from the running program.

    For starters: you said later that 'n' was initialized --- well, in the source you show it rather clearly is not (or rather: only half the time). You also said

    The variable looks something like this the first time: "0123"

    and the second time: "0123123"


    If so, you must have caused undefined behaviour, since code_char is only 5 characters long, so there's absolutely no way it could ever hold an 8-byte string like the above.

Children
More questions in this forum