Shantanu Tomar
Shantanu Tomar

Reputation: 1712

How to append a string in front of string in C

I have a string in C : "Phone/mis. ie Credit Card pmnt". Its length is 30 chars. I want to append a string in front of this "R*". So that my final output stands as "R* Phone/mis. ie Credit Card p". String truncates over here at the end as its max length is 30 chars. I have tried below code where iov_pPymArr->pymInfoArray[i].type_desc variable contains string "Phone/mis. ie Credit Card pmnt":

sprintf (iov_pPymArr->pymInfoArray[i].type_desc,"R*%s",iov_pPymArr->pymInfoArray[i].type_desc);

But it gives me output as : "R*R*e/mis. ie Credit Card pmnt". 

R* is getting appended twice and string is getting truncated from beginning instead of end. Please advice the possible Solution.

Upvotes: 1

Views: 3771

Answers (4)

Magisch
Magisch

Reputation: 7352

Writting a Buffer into itself using sprintf is undefined and not legal means of coding. Use strcat or a temporary buffer instead.

Upvotes: 0

Petr Skocik
Petr Skocik

Reputation: 60068

If you want to absolutely minimize your memory usage and your string buffer is large enough, you can use memmove to make space at the front of it (from the space past the null terminator which needs to be there unless you want a segfault) and then memcpy the prefix to the front, without the terminating zero.

#define STR " Phone/mis. ie Credit Card p"
#define PREFIX "R*"

#include <stdio.h>
#include <string.h>
int main(){
  char buff[sizeof(STR) + 2] = STR;
  memmove(buff + 2, buff, sizeof(buff) - 2);
  memcpy(buff, PREFIX, 2);
  puts(buff);
}

Output:

R* Phone/mis. ie Credit Card p

Note: Appending in the front is called prepending.

Upvotes: 1

ypnos
ypnos

Reputation: 52347

You cannot use sprintf in-place. The solution to your problem is to use a temporary buffer.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409186

Using sprintf to write a buffer to itself is undefined behavior.

Use sprintf (or even better, snprintf) to write to another temporary buffer, and copy that to the actual buffer.

Upvotes: 5

Related Questions