问题描述
我不明白为什么下面的示例编译和工作:
I don't understand why the following example compiles and works:
void printValues(int nums[3], int length) {
for(int i = 0; i < length; i++)
std::cout << nums[i] << " ";
std::cout << '\n';
}
似乎3的大小完全被忽略,在编译错误。这是怎么回事?
It seems that the size of 3 is completely ignored but putting an invalid size results in a compile error. What is going on here?
推荐答案
在C ++(以及C)中,以数组类型声明的参数总是立即衰减到指针类型。以下三个声明是等效的
In C++ (as well as in C), parameters declared with array type always immediately decay to pointer type. The following three declarations are equivalent
void printValues(int nums[3], int length);
void printValues(int nums[], int length);
void printValues(int *nums, int length);
大小没有关系。但是,它并不意味着你可以使用一个无效的数组声明,例如,指定一个负或零大小是非法的。例如:
I.e. the size does not matter. Yet, it still does not mean that you can use an invalid array declaration there, i.e. it is illegal to specify a negative or zero size, for example.
(BTW,这同样适用于函数类型的参数 - 它立即衰减到指针到函数类型。)
(BTW, the same applies to parameters of function type - it immediately decays to pointer-to-function type.)
如果要强制参数和参数之间的数组大小匹配,请使用参数声明中的指针或数组类型
If you want to enforce array size matching between arguments and parameters, use pointer- or reference-to-array types in parameter declarations
void printValues(int (&nums)[3]);
void printValues(int (*nums)[3]);
当然,在这种情况下,大小将成为编译时常量, length
。
Of course, in this case the size will become a compile-time constant and there's no point of passing length
anymore.
这篇关于为什么可以在函数参数中指定数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!