-1

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?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
albertR
  • 321
  • 1
  • 3
  • 6

2 Answers2

3

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

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
3

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);
}
Gopi
  • 19,784
  • 4
  • 24
  • 36
  • 2
    Couple of suggestion to add to this answer: take strlen(a) + strlen(b) + 1 as the size instead of hard coding it to 20, and remember to check for malloc failures to avoid GPF/Segfault. – Chris Nov 11 '14 at 16:50
  • @Chris Just showed how it can be done but agree with you hardcoding is never a good idea – Gopi Nov 11 '14 at 16:52
  • completely understood, not inferring in anyway anything negative :) I like to take advantage in these types of questions to expose such considerations to new developers if I can. Good skills for the future and all that. Cheers. – Chris Nov 11 '14 at 16:56