为什么这个程序不打印串联字符串?

Shu*_*aik 0 c

用于连接字符串的代码

    #include<stdio.h>
    char *concat(char *p1,char *); //function decalaration
    int main(void)
    {
        char a[100],b[100],*q=NULL;  //declare two char arrays
        printf("Enter str1:");
        scanf("%s",a);
        printf("Enter str2:");
        scanf("%s",b);
        q=concat(a,b);     //calling str concat function
        printf("Concatenated str:%s\n",q);
        return 0;
    } 
    char *concat(char *p1,char *p2) //function to concatenate strings 
    {
        while(*p1!='\0')
        p1++;
        while(*p2!='\0')
        {
                *p1=*p2;
                p1++;
                p2++;
        }
        *p1='\0';
        printf("Concatenated str=%s\n",p1); //printing the concatenated string
        return p1; //returning pointer to called function
    }
Run Code Online (Sandbox Code Playgroud)

//虽然逻辑是正确的,但它没有显示输出.//为什么这段代码不起作用?

P.P*_*.P. 5

您正在返回p1,而不是指向连接字符串的开头.您只需要保存原件并将其退回.

   char *concat(char *p1,char *p2) //function to concatenate strings
    {
    char *org = p1;

    ...
    return org;
    }
Run Code Online (Sandbox Code Playgroud)