You can use sprintf
to write a formatted number to a string, and you can use snprintf
to find out how many characters are required.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Return a newly allocated string containing String followed by Number
converted to decimal. The caller is responsible for freeing the memory.
*/
static char *ConcatenateIntToString(const char *String, int Number)
{
// Get the number of non-null characters in String.
size_t Length = strlen(String);
/* Allocate space for:
the characters in String,
the characters needed to format Number with "%d", and
a terminating null byte.
*/
char *Result = malloc(
Length
+ snprintf(NULL, 0, "%d", Number)
+ 1);
// Test whether the allocation succeeded.
if (!Result)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
// Copy the characters from String.
memcpy(Result, String, Length);
// Append the formatted number and a null terminator.
sprintf(Result + Length, "%d", Number);
// Return the new string.
return Result;
}
int main(void)
{
char *NewString = ConcatenateIntToString("CAT ", 11);
printf("The new string is %s.\n", NewString);
free(NewString);
}