Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to use strcat() with a string and int?

I'm try to concatenate to char * rv with the result of a function call that will return an int. fib() returns an int. The main problem I'm running into is that strcat()'s signature requires a const char * as it's second arg:

char * strcat ( char * destination, const char * source );

Here is a small sample of my code. fib() calculates the nth fibonacci number - in this case, the 7th fibonacci number.

char * rv;
int num;

rv = (char*)malloc(2048*sizeof(char));
num = 7;

...

strcat(rv, (const char *)itoa(fib(num), rv,10));

Obviously this is wrong and won't compile. What is the cleanest way to do this? Do I need another char * var to store the results of itoa() first, instead of using rv?

Thank you for any help you can provide!

like image 765
iaacp Avatar asked Sep 15 '25 08:09

iaacp


2 Answers

Use snprintf() to construct a buffer containing the int and then concatenate it to your rv buffer. Do not attempt to concatenate the existing content of rv in the same call to snprintf():

snprintf(rv, 2048, "%s%d", rv, itoa(fib(num), rv,10)));

as this means the input and output buffers overlap which is undefined behaviour.

Also:

  • sizeof(char) is guaranteed to be 1
  • see Do I cast the result of malloc?

So the malloc() call would be:

rv = malloc(2048);
if (rv)
{
}
like image 122
hmjd Avatar answered Sep 17 '25 00:09

hmjd


You need either an intermediate char array to print the number to before strcating, or you can directly sprintf the number to rv, but for that you need a pointer to the end,

char *rv = malloc(2048);
char *rv_end = rv;
...
rv_end += sprintf(rv_end, "%d", fib(num));

and also update the rv_end pointer when appending other things to the buffer.

(Thanks to jthill for the improvement using the return value of sprintf.)

like image 22
Daniel Fischer Avatar answered Sep 16 '25 23:09

Daniel Fischer