C string concatenation – Education Career Blog

I am trying to input 2 strings in C, and output a 3rd string which the concatenation of string 1 and 2.

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

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

    char stringarray1 30;
    char stringarray2 30;
    char stringarray3 30;

    int length;

    printf("Please enter some text less than 30 characters long\n");
    scanf("%a-z, ", &stringarray1);

    printf("Please enter some text less than 30 characters long\n");
    scanf("%a-z, ", &stringarray2);

    strcat(stringarray1, stringarray2);


    //length = strlen(stringarray);
    printf("The combined string is %s\n", stringarray1);


    return (EXIT_SUCCESS);
}

It allows me to input the first string, but then prints the seond and third printf statement, without allowing me to enter the second string.

How can i enter the second string without it exiting? Why does it exit?

,

Have a look at the documentation of scanf: Your format string "%a-z, " does not what you seem to think what it does. Just use "%s" for strings instead. (It’s without any character checks).

,

You should not put the & for your arrays that are already pointers.

scanf("%a-z, ", stringarray2);

,

At a guess, I’d say you need a \n inside your scanf specification strings. You should probably also be asking for %s instead of %a-z, . The way you have it a single character would match, then when the second scanf is hit, the next character would match.

Also there are some safety issues. You should probably be checking to make sure both strings together aren’t larger than 30 chars. As Benoit pointed out, arrays in C also double as pointers to the first character, so you don’t use the address-of operator (&) on them when passing them to the C IO routines. That would give the routine the address of your array pointer itself, which the IO routine would then merrily wipe out with character data. Not good!

,

You know the difference between an chararray a stringarray? I think not. Also you must allocate enough space for you result-string, like:

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

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

    char chararray1 31;
    char chararray2 16;
    char chararray3 30;

    int length;

    printf("Please enter some text less than 15 characters long\n");
    scanf("%15a-z, ", stringarray1);

    printf("Please enter some text less than 15 characters long\n");
    scanf("%15a-z, ", stringarray2);

    strcat(stringarray1, stringarray2);


    //length = strlen(stringarray);
    printf("The combined string is %s\n", stringarray1);


    return (EXIT_SUCCESS);
}

,

I would recommend using fgets instead of scanf, that you can specify a max length (buffer target size – 1) and avoid surprises.

also the target buffer should be twice the size of your input buffers otherwise you risk a memory overwrite

Leave a Comment