这不是错误的,因为数组永远不能按值传递吗?
确切地。您不能在 C 中按值传递数组。
我看了一下书中引用的部分,很快就找到了这种混乱或错误的根源。
作者不知道这*i
相当于i[]
何时作为参数提供给函数。发明后一种形式是为了明确说明代码的读者,它i
指向一个数组,这是一个很大的混淆来源,正如这个问题所展示的那样。
我认为有趣的是,这本书特定部分的作者或其他部分中的至少一个(因为这本书总共有5位作者)或7位校对者中的一位至少没有提到这句话:
"当byval_func()
函数被调用时,你将数组的地址byval_func()
传递给: "
至少,他们应该注意到有冲突。由于您传递了一个地址,因此它只是一个地址。没有什么神奇的事情可以将地址变成一个全新的数组。
但回到问题本身:
您不能在 C 中按值传递数组,因为您似乎已经了解自己。但是您可以做三件事(可能还有更多,但这是我的实际情况),这可能是根据独特情况的替代方案,所以让我们开始吧。
- 将数组封装在结构中(如其他答案所述):
#include <stdio.h>
struct a_s {
int a[20];
};
void foo (struct a_s a)
{
size_t length = sizeof a.a / sizeof *a.a;
for(size_t i = 0; i < length; i++)
{
printf("%d\n",a.a[i]);
}
}
int main()
{
struct a_s array;
size_t length = sizeof array.a / sizeof *array.a;
for(size_t i = 0; i < length; i++)
{
array.a[i] = 15;
}
foo(array);
}
- 通过指针传递,还要添加一个参数来确定数组的大小。在被调用的函数中,使用该大小信息创建了一个新数组,并分配了调用者中数组中的值:
#include <stdio.h>
void foo (int *array, size_t length)
{
int b[length];
for(size_t i = 0; i < length; i++)
{
b[i] = array[i];
printf("%d\n",b[i]);
}
}
int main()
{
int a[10] = {0,1,2,3,4,5,6,7,8,9};
foo(a,(sizeof a / sizeof *a));
}
- 避免定义本地数组,只使用一个具有全局范围的数组:
#include <stdio.h>
int a[10];
size_t length = sizeof a / sizeof *a;
void foo (void)
{
for(size_t i = 0; i < length; i++)
{
printf("%d\n",a[i]);
}
}
int main()
{
for(size_t i = 0; i < length; i++)
{
a[i] = 25;
}
foo();
}