This question already has an answer here:
-
How do I concatenate const/literal strings in C?
17 answers
What I have:
char * a = "world";
char * b = "Hello";
What I need is:
char * a = "Hello World";
I need to add b before a.
Is there any function that doing it?
It can be done easily as shown below:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
char * a = "world";
char * b = "Hello";
char *c = malloc(strlen(a)+strlen(b)+1);
strcpy(c,b);
strcat(c,a);
printf("%s\n",c);
free(c);
}
You could use strcat(3), snprintf(3) or asprintf(3)
With strcat
you need to check against buffer overflow (using strlen(3)...)
With strcat
& snprintf
, you need to pre-allocate the array.
With asprintf
you are given a heap-allocated buffer as a result, and you'll need to free
it appropriately.
So, using strcat
and a fixed-size buffer buf
:
char buf[64];
if (strlen(a)+strlen(b)<sizeof(buf)) {
strcpy(buf, a);
strcat(buf, b);
}
// now buf contains "worldhello"
Alternatively you might use a heap-allocated buffer:
char*buf = malloc(strlen(a)+strlen(b)+1);
but don't forget to check against malloc
failure: if (!buf) { perror("malloc buf"); exit(EXIT_FAILURE); };
and then do the strcpy
& strcat
as before. Of course you'll need to free(buf)
later at the appropriate time. Notice that you could keep int lena=strlen(a);
then strcpy(buf+lena,b)
instead of calling strcat
.
Using snprintf
and a fixed-size buffer buf
(no need to check against buffer overflow since snprintf
is given the buffer size):
char buf[54];
int len= snprintf(buf, sizeof(buf), "%s%s", a, b);
// now buf contains "worldhello" and len contains the required length
The nice thing about snprintf
is that is understands printf
format control strings (e.g. %d
for integer in decimal, %g
for floating point in scientific notation, etc...)
Using asprintf
(on systems like Linux which provide it)
char* buf = asprintf("%s%s", a, b);
But you need to call free(buf)
at the appropriate moment to avoid a memory leak.
See also strdup(3), fmemopen(3) and open_memstream
In your question you should swap a
and b