|
W3School讲得很浅:C++ Pass Array to a Function,只说了如何将数组传给函数.
比如要计算整型的数组l1的长度,
- #include<stdio.h>
- int main() {
- int l1[] = { 9, 9, 9, 9, 9, 9, 9 };
- printf("%d", (int)(sizeof(l1) / sizeof(int)));
- return 0;
- }
复制代码
打印结果为 7, 是所预期的. 但如果做成一个“以数组为参数”的函数:
- #include<stdio.h>
- void func(int l1[]) {
- printf("%d", (int)(sizeof(l1) / sizeof(int)));
- }
- int main() {
- int l1[] = { 9, 9, 9, 9, 9, 9, 9 };
- func(l1);
- return 0;
- }
复制代码
打印结果却是 2. 这是因为sizeof(l1)是计算“指针类型int*的size”, (在CPU architecture是x64情况下)是8字节, 所以是int的size的两倍. 而且gcc会发出警告:
'sizeof' on array function parameter 'l1' will return size of 'int *' [-Wsizeof-array-argument] |
|
又见stackoverflow.com/questions/6567742
When passing an array as a parameter, this
void arraytest(int a[])
means exactly the same as
void arraytest(int *a)
For historical reasons, arrays are not first class citizens and cannot be passed by value. |
|