我的程序
#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
}
输出:
readers
helloreaders
连接后:
helloreaders
我只返回来自 mystrcat()
的源字符串。但是编译器如何知道修改后的目标字符串呢?由于我全局声明该函数,编译器知道修改后的字符串吗?
最佳答案
这不是因为 return sr
,而是因为 char* mystrcat(char* des, char *sr)
修改了它的参数 ( des
)。即使将返回值更改为 int,结果也是相同的。原因是当您将 char[]
变量传递给函数时,您只需传递一个指针,您在函数内对变量所做的任何操作都会反射(reflect)给调用者。
关于c - 编译器如何在没有函数接收者数组的情况下获取正确的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29576817/