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,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/

相关文章:

C程序: Convert string of chars representing numbers to ints

c - 如何提供 OpenSSL 随机数据以用于 ECDSA 签名?

c++ - 寻找最近的较小素数的快速算法

c - int expecting 发现语法错误; C ICC12 编译器

c - GCC 无法识别文件内的目录路径

c - 获取C中指针的大小

c - 当我的字符串有 4-5 个字符时,write() 会添加填充吗?

c - 如何像在 Autotools 中一样检查 CMake 中的头文件和库函数?

c - 带有 CUDA 5.5 的 Visual Studio 2012 - 无法识别 CUDA 语法和定义

C 共享库 : static variable initialization + global variable visibility among processes