为什么我们不能通过值传递数组来函数?数组、函数

2023-09-06 18:11:06 作者:后来的结果

显然,我们可以将复杂的类实例传递给函数,但是为什么我们不能将数组传递给函数呢?

Apparently, we can pass complex class instances to functions, but why can't we pass arrays to functions?

推荐答案

起源是历史的.问题是数组在传递给函数时衰减为指针"的规则很简单.

The origin is historical. The problem is that the rule "arrays decay into pointers, when passed to a function" is simple.

复制数组会有点复杂而且不是很清楚,因为行为会因不同的参数和不同的函数声明而改变.

Copying arrays would be kind of complicated and not very clear, since the behavior would change for different parameters and different function declarations.

请注意,您仍然可以通过值进行间接传递:

Note that you can still do an indirect pass by value:

struct A { int arr[2]; };
void func(struct A);
 
精彩推荐
图片推荐