Search code examples
cstringstring-concatenation

Concatenate first characters from a command line argument in c


I have tried this solution, but don't know why it is giving segmentation fault.

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

int main(int argc, char *argv[])
{
    char st[1000]="";
    for (int i=1; i<argc; i++)
    {

            strcat(st,argv[i][0]);
            strcat(st,". ");

    }
    printf("%s", st);

    return 0;
}

Solution

  • Change this statement

            strcat(st,argv[i][0]);
    

    to

            strncat(st, &argv[i][0], 1);
    

    or

            strncat(st, argv[i], 1);
    

    In the original statement the function considers the character argv[i][0] as a pointer value. So the call has undefined behavior.

    Or you can use a straightforward approach without using string functions. For example

    #include <stdio.h>
    
    int main( int argc, char * argv[] ) 
    {
        char st[1000];
        size_t i = 0;
    
        for ( int j = 1; j < argc; j++ )
        {
            st[i++] = *argv[j];
            if ( j + 1 != argc )
            {
                st[i++] = ',';
                st[i++] = ' ';
            }           
        }
    
        st[i] = '\0';
    
        puts( st );
    
        return 0;
    }