当一个函数有一个特定大小的数组参数,为什么它的指针取代? [英] When a function has a specific-size array parameter, why is it replaced with a pointer?
问题描述
由于下面的程序,
的#include<&iostream的GT;使用命名空间std;无效美孚(CHAR [100])
{
COUT<< 富()<<的sizeof(a)及所述;&下; ENDL;
}诠释的main()
{
炭棒[100] = {0};
COUT<< 主要()<<的sizeof(巴)LT;< ENDL;
富(巴);
返回0;
}
输出
的main()100
富()4
- 为什么数组指针传递给第一个元素?
- 它是从C? 文物
- 这是什么标准说什么?
- 为什么是C的严格类型安全++下降?
是的,它是从C继承的功能:
无效美孚(CHAR [100]);
将有调整到一个指针参数,所以就变成了:
无效美孚(字符*一);
如果您希望该数组类型是preserved,你应该通过在对数组的引用:
无效美孚(CHAR(安培;一)[100]);
C ++ 8.3.5 '03 / 3:
...的类型的函数的是使用以下规则来确定。的每个参数的类型是从它自己的DECL说明符-SEQ和说明符来确定。确定每个参数的类型,类型的任何参数阵列的T或函数返回T之后被调整为指针T或分别指针返回T的函数,...
块引用>为了解释的语法:
为您在谷歌右左的规则;我发现它的一个描述href=\"http://www.cpp-home.com/archives/106.html\"> 。
这将如下近似应用于此示例:
无效美孚(CHAR(安培;一)[100]);
在开始识别符A
A是一个
块引用>向右移动 - 我们找到了
)
让我们反方向寻找(
当我们向左移动我们。通过&安培;
A是一个参考。
块引用>在
&放大器;
我们到达开幕(
让我们再次扭转和看的权利,我们现在看到的[100]
A是100的数组
参考
块引用>和我们再次改变方向,直到我们达到
字符
:
A是100字符数组
参考
块引用>Given the following program,
#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; }
outputs
main() 100 foo() 4
- Why is the array passed as a pointer to the first element?
- Is it a heritage from C?
- What does the standard say?
- Why is the strict type-safety of C++ dropped?
解决方案Yes it's inherited from C. The function:
void foo ( char a[100] );
Will have the parameter adjusted to be a pointer, and so becomes:
void foo ( char * a );
If you want that the array type is preserved, you should pass in a reference to the array:
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....
To explain the syntax:
Check for "right-left" rule in google; I found one description of it here.
It would be applied to this example approximately as follows:
void foo (char (&a)[100]);
Start at identifier 'a'
'a' is a
Move right - we find a
)
so we reverse direction looking for the(
. As we move left we pass&
'a' is a reference
After the
&
we reach the opening(
so we reverse again and look right. We now see[100]
'a' is a reference to an array of 100
And we reverse direction again until we reach
char
:'a' is a reference to an array of 100 chars
这篇关于当一个函数有一个特定大小的数组参数,为什么它的指针取代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!