我很难理解为什么在 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 使用以将其打印出来。