当一个函数有一个特定大小的数组参数,为什么它的指针取代? [英] When a function has a specific-size array parameter, why is it replaced with a pointer?

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

问题描述

由于下面的程序,

 的#include<&iostream的GT;使用命名空间std;无效美孚(CHAR [100])
{
    COUT<< 富()<<的sizeof(a)及所述;&下; ENDL;
}诠释的main()
{
    炭棒[100] = {0};
    COUT<< 主要()<<的sizeof(巴)LT;< ENDL;
    富(巴);
    返回0;
}

输出

 的main()100
富()4


  1. 为什么数组指针传递给第一个元素?

  2. 它是从C?
  3. 文物
  4. 这是什么标准说什么?

  5. 为什么是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

  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天全站免登陆