Search code examples
cnewlinec-stringsfgetsstrcat

Combining strings with fixed size arrays


Let's take the following example code where I concatenate two fixed-sized arrays together:

int main(void) {
    char first_name[20], last_name[20], full_name[40];
    puts("First Name?"); 
    fgets(first_name, 20, stdin);
    puts("Last Name?");  
    fgets(last_name, 20, stdin);
    strcat(full_name, first_name);
    strcat(full_name, " ");
    strcat(full_name, last_name);
    puts(full_name);
}

Assuming the first/last names are under 20 chars, this will produce output such as:

Robert                        Diaz

Is this because the full_name has not been initialized, or due to how strcat works? What would be a better way to do this?


Solution

  • For starters the program has undefined behavior because the array full_name was not initialized and does not contain a string.

    char first_name[20], last_name[20], full_name[40];
    

    So you may not use strcat to append a string to a non-existent string.

    Another problem is that the function fgets can append the new line character '\n' to the read string. You should remove it.

    The program can look the following way

    #include <stdio.h>
    #include <string.h>
    
    int main(void) 
    {
        enum { N = 20 };
        char first_name[N], last_name[N], full_name[2 * N];
        
        puts( "First Name?" ); 
    
        fgets( first_name, N, stdin );
        first_name[ strcspn( first_name, "\n" )] = '\0';
        
        puts( "Last Name?" ); 
        
        fgets( last_name, N, stdin );
        last_name[ strcspn( last_name, "\n" )] = '\0';
    
        strcpy( full_name, first_name );
        strcat( full_name, " " );
        strcat( full_name, last_name );
        
        puts( full_name );
    }
    

    The program output might look like

    First Name?
    Robert
    Last Name?
    Disz
    Robert Diaz