首页 > 代码库 > 由C/C++函数的参数列表中的数组长度所想
由C/C++函数的参数列表中的数组长度所想
Why do C and C++ compilers allow array lengths in function signatures when they‘re never enforced?
这个是由于,很久前的一次(其实也没多久),编程过程中发现这种情况
#include<iostream>
using namespace std;
int dis(char a[1])
{
int length = strlen(a);
char c = a[2];
return length;
}
int main()
{
char b[4] = "abc";
int c = dis(b);
cout << c;
return 0;
}
函数dis中的参数a[1]后的数字1,根本不起作用,其实写2.3.4都可以,这也是很多人都知道的,本着探究的精神多想了一点,既然不起作用,那么为什么不禁止这种行为,依然还是到了stackoverflow(真的是神站)上提问,得到了众多大神的解答Why do C and C++ compilers allow array lengths in function signatures when they‘re never enforced?
这是一个比较好的回答
It is a quirk of the syntax for passing arrays to functions.
Actually it is not possible to pass an array in C. If you write syntax that looks like it should pass the array, what actually happens is that a pointer to the first element of the array is passed instead.
Since the pointer does not include any length information, the contents of your []
in the function formal parameter list are actually ignored.
The decision to allow this syntax was made in the 1970s and has caused much confusion ever since...
其他精彩的回答,具体可以看这里,就不搬过来了。。http://stackoverflow.com/questions/22677415/why-do-c-and-c-compilers-allow-array-lengths-in-function-signatures-when-they
由C/C++函数的参数列表中的数组长度所想