Concatenating Strings in C

As I continue studying for finals, I came across the realization that this is something a lot of people are having trouble with.  While there is a standard string library function to concatenate strings, there are a lot of other means that provide for a great amount of flexibility in formatting.

Here is a simple example in C to do a straight concatenation using the sprintf function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *concat(char *str1, char *str2) {
char *conc = (char *)malloc(sizeof(char)*(strlen(str1)+strlen(str2)+1));
sprintf(conc, “%s%s”, str1, str2);
return conc;
int main() {
char hello[10] = “Hello “;
char world[10] = “World!”;
char *hw = concat(hello, world);
printf(“%s\n”, hw);
return 0;

This is a simple example, but one that shows how easy it can be to work with strings in C.  What this does is it starts in main by creating two strings which can hold 9 characters and initializes them to “Hello ” and “World!”.  It then passes the addresses of these two arrays into a function I wrote called concat.

Once in concat, I create a brand new array on the heap that is perfectly sized for the non-null characters inside of these strings, along with an extra space for the new null terminator.   sprintf then enables me to format a normal string for printing with all sort of elaborate options.  In this case, I’m doing a simple concatenation, so my format codes are “%s%s”.  The arguments are my two string parameters.   sprintf creates this new string using the format codes and places the characters into the array specified by my string pointer to the heap array, which is the first argument.

Once I return, I am now free to use this new concatenated string as I wish.  Of course, I will free it when I am done.

Now, this was just a simple example.  Below are some examples of creative sprintf uses I have used in the last few weeks of classes:

sprintf(message, “Person [%d]: Notification that a %s is leaving the room.\n”, id, gender?”male”:”female”);

sprintf(variable->label, “g_%s%d”, name, varctr++);

Just was thinking about this as I was looking at materials for finals.


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>