Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 编译器如何在没有接收数组的情况下从函数中获取正确的字符串?_C - Fatal编程技术网

C 编译器如何在没有接收数组的情况下从函数中获取正确的字符串?

C 编译器如何在没有接收数组的情况下从函数中获取正确的字符串?,c,C,我的节目 #include<stdio.h> #include<conio.h> char* mystrcat(char* , char* );\\ function declared as global main() { char dest[50]="hello"; \\destination string char src[50]="readers"; \\source string clrscr(); mystrcat(dest

我的节目

#include<stdio.h>
#include<conio.h>
char* mystrcat(char* , char* );\\ function declared as global
main()
{

    char dest[50]="hello";  \\destination string
    char src[50]="readers";  \\source string
    clrscr();
    mystrcat(dest,src);\\function calling but does not have receiving array 
    puts("after concatenation");                              \\ of strings
    puts(dest);\\shows "helloreaders"<-- how?
    getch();
    return 0;

}
char* mystrcat(char* des, char *sr)\\for concatenating two strings
{

    int i=0,j=0;
    while(des[i]!='\0')
    { i++;}
    while(sr[j]!='\0')  
    {
        des[i]=sr[j];
        i++;j++;

    }
    des[i]='\0';
    puts(sr);\\"readers"
    puts(des);\\"helloreaders"
    return sr;\\returning source string

}
连接后:

  helloreaders

我只从
mystrcat()
返回源字符串。但编译器如何知道修改后的目标字符串呢?由于我全局声明函数,编译器知道修改的字符串?

这不是因为
返回sr
,而是因为
char*mystrcat(char*des,char*sr)
修改了它的参数(
des
)。即使将返回值更改为一个int,结果也是一样的。原因是当您将一个
char[]
变量传递给函数时,您只需传递一个指针,您在函数内部对该变量所做的任何操作都将反映给调用者。

因为传递给函数的参数是点,它们指向的数组会发生更改,但调用函数时这些点不会发生更改

mystrcat(dest,src);\\function calling but does not have receiving array 
您作为参数传递了两个数组,它们隐式转换为指向每个数组的第一个元素的指针

因此,在函数中,处理数组所占用的内存块的地址。然后写入源数组的目标数组元素所占用的内存

while(sr[j]!='\0')  
{
 des[i]=sr[j];
 i++;j++;
 }
 des[i]='\0';
因为
des
sr
保存数组第一个元素的地址


因此,数组
dest
占用的内存被覆盖。

您给mystrcat()一个指向dest的指针,当它通过该指针写入时,它会直接更改dest。函数返回什么并不重要。mystrcat()中的des[]不是主程序中dest[]的副本,它是同一件事。

它编译吗?行注释的正确分隔符为
/
while(sr[j]!='\0')  
{
 des[i]=sr[j];
 i++;j++;
 }
 des[i]='\0';