why the string is getting altered after strcat()?

前端 未结 4 618
一向
一向 2021-01-27 22:20

this is the source code

int main()
{
    char str[]=\"dance\";
    char str1[]=\"hello\";
    char str2[]=\"abcd\";
    strcat(str1,str2);
    printf(\"%s\",s         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-27 22:51

    str1 has not enough space to concatenate the string str2. This invokes undefined behavior. You may get anything. Either expected or unexpected result.
    Now try this:

    #include 
    #include  
    
    int main(void) {
        char str[]="dance";
        char str1[10]="hello";
        char str2[]="abcd";
        strcat(str1,str2);
        printf("%s\n",str1);
        printf("%s\n",str);
    
        return 0;
    }  
    

    Output:

    helloabcd
    dance
    

提交回复
热议问题