当函数有特定大小的数组参数时,为什么要用指针替换它?
给定以下程序,
#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++ 的严格类型安全被放弃了?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,它是从 C 继承的。函数:
将参数调整为指针,因此变为:
如果您希望保留数组类型,则应传入对数组的引用:
C++ '03 8.3 .5/3:
To解释一下语法:
检查google中的“从右到左”规则;我在此处找到了它的描述。
它将大致如下应用于此示例:
从标识符“a”开始
向右移动 - 我们找到
)
,因此我们反向寻找(
。当我们向左移动时,我们通过&
在
&
之后,我们到达开头(
,因此我们再次反转并向右看。我们现在看到[100]
,我们再次反转方向,直到到达
char
:Yes it's inherited from C. The function:
Will have the parameter adjusted to be a pointer, and so becomes:
If you want that the array type is preserved, you should pass in a reference to the array:
C++ '03 8.3.5/3:
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:
Start at identifier 'a'
Move right - we find a
)
so we reverse direction looking for the(
. As we move left we pass&
After the
&
we reach the opening(
so we reverse again and look right. We now see[100]
And we reverse direction again until we reach
char
:是的。在 C 和 C++ 中,不能将数组传递给函数。事情就是这样。
你为什么还要做普通数组?您看过
boost
/std::tr1::array
/std::array
或std::vector
>?但是请注意,您可以将对任意长度的数组的引用传递给函数模板。从我的头顶上掉下来:
Yes. In C and C++ you cannot pass arrays to functions. That's just the way it is.
Why are you doing plain arrays anyway? Have you looked at
boost
/std::tr1::array
/std::array
orstd::vector
?Note that you can, however, pass a reference to an array of arbitrary length to a function template. Off the top of my head:
C/C++ 术语中有一个用于静态数组和函数指针的华丽词 - decay。
考虑以下代码:
There is magnificent word in C/C++ terminology that is used for static arrays and function pointers - decay.
Consider the following code: