给定以下程序,
#include <iostream>
using namespace std;
void foo( char a[100] )
{
cout << "foo() " << sizeof( a ) << endl;
}
int main()
{
char bar[100] = { 0 };
cout << "main() " << sizeof( bar ) << endl;
foo( bar );
return 0;
}
输出
main() 100
foo() 4
- 为什么将数组作为指向第一个元素的指针传递?
- 它是 C 语言的遗产吗?
- 标准是怎么说的?
- 为什么取消了 C++ 的严格类型安全?
最佳答案
是的,它继承自C。函数:
void foo ( char a[100] );
将参数调整为指针,因此变为:
void foo ( char * a );
如果你想保留数组类型,你应该传入对数组的引用:
void foo ( char (&a)[100] );
C++ '03 8.3.5/3:
...The type of a function is determined using the following rules. The type of each parameter is determined from its own decl-specifier-seq and declarator. After determining the type of each parameter, any parameter of type "array of T" or "function returning T" is adjusted to be "pointer to T" or "pointer to function returning T," respectively....
语法解释:
在谷歌中检查“右-左”规则;我找到了一个描述 here .
它将大致如下应用于此示例:
void foo (char (&a)[100]);
从标识符 'a' 开始
'a' is a
向右移动 - 我们找到一个 )
所以我们反向寻找 (
。当我们向左移动时我们通过 &
'a' is a reference
在 &
之后我们到达开头 (
所以我们再次反转并向右看。我们现在看到 [100]
'a' is a reference to an array of 100
然后我们再次反转方向,直到到达 char
:
'a' is a reference to an array of 100 chars
关于c++ - 当一个函数有一个特定大小的数组参数时,为什么它被替换为一个指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54629280/