1

我很难理解为什么在 main 之外的函数中连接的字符串能够在 main 函数中打印出来。简而言之,该程序旨在说明两个 char 数组的串联。

#include <stdio.h>

void concat(char result[], const char str1[], int n1, const char str2[], int n2)
{
    int i, j;

    // copy str1 to result
    for (i = 0; i < n1; ++i)
    {
        result[i] = str1[i];
    }
    // copy str2 to result
    for (j = 0; j < n2; ++j)
    {
        result[n1 + j] = str2[j];
    }
}

int main(void)
{
    void concat(char result[], const char str1[], int n1, const char str2[], int n2);
    const char s1[5] = { 'T', 'e', 's', 't', ' ' };
    const char s2[6] = { 'w', 'o', 'r', 'k', 's', '.' };
    char s3[11];
    int i;

    concat(s3, s1, 5, s2, 6);

    for (i = 0; i < 11; ++i)
    {
        printf("%c", s3[i]);    // Here is what I do not understand: how was the s3 array
                                // accessible since it was not returned from concat
    }
    printf("\n");

    return 0;
}

据我了解,除非函数返回一个值或数组/变量是全局声明的(这是一个应该尽量避免的事情:我们想要一个紧凑的范围),那么数组/变量不应该对主要的“可见”?这不正确吗?因为我认为 s3 需要从函数中返回以供 main 使用以将其打印出来。

4

3 回答 3

1

可以在数组可见的任何地方访问和修改数组中的值。在这种情况下,您正在更改“concat”方法中的数组。数组是对这些值的引用,因此当您不返回这个新数组时,当您更改数组的元素时,它们会在引用数组的任何地方发生更改。

于 2013-10-30T01:45:52.477 回答
1

C 中的函数使用按值传递参数。当您将 s3 作为 concat 的第一个参数传递时,您传递的值是“数组 s3 的地址”。函数 concat 使用该地址作为您命名为 result 的参数的位置。该函数将值复制到内存位置结果(这是调用函数中 s3 的另一个名称)。

当函数到达函数 concat 的末尾时,s3 处的数组已被修改。

为了说明这一点,在调用 concat 之前打印出 s3 的地址,

printf("s3 address: %x\n",s3);

然后在concat里面打印出result的地址,

printf("result address: %x\n",result);

您作为 s3 传递的值是 s3[] 的地址,它是对 char[11] 内存缓冲区的引用。

于 2013-10-30T01:59:25.270 回答
0

实际上,您的程序是通过输出参数概念获得输出的。我应该编写一个名为 Result 的 void 函数,它只有三种类型的 int 输入/输出参数。该函数将通过第一个参数返回两个原始参数的和。. 我不知道我这样做是否正确,但我不知道这对你有帮助吗?

02

#include <stdlib.h>
03  #include <stdio.h>
04   
05  void result(int *sum, int a,int b);
06   
07  int
08  main(void)
09  {
10            int  num1, num2,sum=0;
11              
12             /* Gets test data */
13             printf("Enter the first number");
14             scanf("%d", &num1);
15             printf("Enter the second number");
16             scanf("%d", &num2);
17             result(&sum,num2, num1)           
18              
19             printf("The first number is %2.d", num1);
20             printf("The second number is %2.d", num2);
21             system("pause");
22             return (0);
23             }
24  void
25  result(int *psum, int *num1,int num2)
26  {
         sum=a+b;
27   }
36                                  
37          
于 2013-10-30T04:18:19.463 回答