当函数具有特定大小的数组参数时,为什么要用指针替换它? [英] When a function has a specific-size array parameter, why is it replaced with a pointer?

查看:21
本文介绍了当函数具有特定大小的数组参数时,为什么要用指针替换它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下程序,

#include 使用命名空间标准;void foo( char a[100] ){cout<<"foo()" <<sizeof(a)<<结束;}int main(){字符栏[100] = { 0 };cout<<主()"<<大小(条)<<结束;富(酒吧);返回0;}

输出

main() 100foo() 4

  1. 为什么将数组作为指向第一个元素的指针传递?
  2. 它是 C 语言的遗产吗?
  3. 标准怎么说?
  4. 为什么取消了 C++ 的严格类型安全?

解决方案

是的,它继承自 C.功能:

void foo ( char a[100] );

将参数调整为指针,从而变成:

void foo ( char * a );

如果你想保留数组类型,你应该传入一个对数组的引用:

void foo ( char (&a)[100] );

C++ '03 8.3.5/3:

<块引用>

...函数的类型使用以下规则确定.每个参数的类型由它自己的 decl-specifier-seq 和 declarator 确定.确定每个参数的类型后,将任何类型为T的数组"或返回T的函数"类型的参数分别调整为指向T的指针"或指向返回T的函数的指针"......

解释语法:

在谷歌中检查右-左"规则;我在此处找到了一个描述.

大致如下应用于此示例:

void foo (char (&a)[100]);

从标识符a"开始

<块引用>

'a' 是一个

向右移动 - 我们找到一个 ) 所以我们反向寻找 (.当我们向左移动时,我们通过 &<块引用>

'a' 是一个引用

& 之后,我们到达了开头的 (,所以我们再次反转并向右看.我们现在看到 [100]

<块引用>

'a' 是对 100 个数组的引用

我们再次反转方向,直到到达char:

<块引用>

'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

  1. Why is the array passed as a pointer to the first element?
  2. Is it a heritage from C?
  3. What does the standard say?
  4. 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆