1

I have two string ta and tb with certain value, then I use the function sprintf to concatenate the two both in the variable ta, when I write

sprintf(ta,"%s+%s",ta,tb);

I get the string 1+2. but I need store in ta the string 2+1 then I trying

sprintf(ta,"%s+%s",tb,ta);

but I get the string 2+2+2+2+. I don't understand why happens that, Could you help me please?. Below the complete code

int main() {
    char ta[5];
    char tb[5];
    sprintf(ta,"%d",1);
    sprintf(tb,"%d",2);
    sprintf(ta,"%s+%s",ta,tb);
    //sprintf(ta,"%s+%s",tb,ta); uncomment for the second case
    printf("taid:%s",ta);
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Juan
  • 2,073
  • 3
  • 22
  • 37

1 Answers1

2
sprintf(ta,"%s+%s",ta,tb);
sprintf(ta,"%s+%s",tb,ta);

Both lines of calling sprintf have undefined behavior. You are trying to copy ta to ta itself.

C11 ยง7.21.6.6 The sprintf function

The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294