1

I know I can have a statement as such

    strcat( a, b );
    int alen = strlen( a );
    printf("a and b concatenated = %s and its length is %d\n", a, alen );

However, I want to preserve a, so I am trying use something more like this:

    strcat( a, b );
    int xlen = strlen( x );
    printf("a and b concatenated = %s and its length is %d\n", x, xlen );

How do I fix the first line with strcat so that it concatenates a and b into x?

tinkerton101
  • 25
  • 1
  • 8

2 Answers2

5

You should use the following :-

strcpy(x,a);
strcat(x,b);
int xlen = strlen(x);
printf("a and b concatenated = %s and its length is %d\n", x, xlen );

Voila,and that's it.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
0

I found that the following as works as well:

    /* Concatenate a and b */
    char x[SIZE1+SIZE2] = “”;
    strcat(x , a );
    strcat(x , b );

    printf("a and b concatenated = %s and its length is %d\n", x, (int)strlen(x) );
tinkerton101
  • 25
  • 1
  • 8
  • 1
    if SIZE1 and SIZE2 are related to strlen(a) and strlen(b) then the result is not large enough, because strlen() is the offset to the trailing NUL byte so need to add +1 to get the proper length. Also, the first line causes x[0] to contain '\0'. it does not clear all of x[]. suggest using: ;char x[SIZE1+SIXE2+1] = {'\0'}; to clear the whole array and to not generate a literal (containing only a '\0' character) in readonly memory – user3629249 Apr 06 '15 at 22:15