Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two char* strings in a C program

Tags:

c

I wrote the following C program:

int main(int argc, char** argv) {

    char* str1;
    char* str2;
    str1 = "sssss";
    str2 = "kkkk";
    printf("%s", strcat(str1, str2));

    return (EXIT_SUCCESS);
 }

I want to concatenate the two strings, but it doesn't work.

like image 447
BeCurious Avatar asked Aug 27 '13 14:08

BeCurious


People also ask

Can you concatenate a char to a string in C?

Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.

How do I combine two characters in a string?

You can use String(char[] value) constructor to convert char array to string.


3 Answers

The way it works is to:

  1. Malloc memory large enough to hold copies of str1 and str2
  2. Then it copies str1 into str3
  3. Then it appends str2 onto the end of str3
  4. When you're using str3 you'd normally free it free (str3);

Here's an example for you play with. It's very simple and has no hard-coded lengths. You can try it here: http://ideone.com/d3g1xs

See this post for information about size of char

#include <stdio.h>
#include <memory.h>

int main(int argc, char** argv) {

      char* str1;
      char* str2;
      str1 = "sssss";
      str2 = "kkkk";
      char * str3 = (char *) malloc(1 + strlen(str1)+ strlen(str2) );
      strcpy(str3, str1);
      strcat(str3, str2);
      printf("%s", str3);

      return 0;
 }
like image 86
dcaswell Avatar answered Oct 06 '22 01:10

dcaswell


Here is a working solution:

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv) 
{
      char str1[16];
      char str2[16];
      strcpy(str1, "sssss");
      strcpy(str2, "kkkk");
      strcat(str1, str2);
      printf("%s", str1);
      return 0;
}

Output:

ssssskkkk

You have to allocate memory for your strings. In the above code, I declare str1 and str2 as character arrays containing 16 characters. I used strcpy to copy characters of string literals into them, and strcat to append the characters of str2 to the end of str1. Here is how these character arrays look like during the execution of the program:

After declaration (both are empty): 
str1: [][][][][][][][][][][][][][][][][][][][] 
str2: [][][][][][][][][][][][][][][][][][][][]

After calling strcpy (\0 is the string terminator zero byte): 
str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][] 
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]

After calling strcat: 
str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][] 
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
like image 22
kol Avatar answered Oct 06 '22 01:10

kol


strcat concats str2 onto str1

You'll get runtime errors because str1 is not being properly allocated for concatenation

like image 3
Sam I am says Reinstate Monica Avatar answered Oct 06 '22 02:10

Sam I am says Reinstate Monica