传数组名的小问题

来源:互联网 发布:威尔取模软件 编辑:程序博客网 时间:2024/04/30 18:57

有人问到传数组名,和数组名引用的问题,平时没怎么使用这么怪异的语法
没有想明白;后来在水木清华上咨询到了清晰的解答,现深入总结如下:
例子:
#include <iostream>
#include <typeinfo>
using namespace std;

void fArray(int *a, int b[], int (*c)[4], int (&ra)[4], int d[4])
{
    cout << "In fArray(...):" << endl;
    cout << "int* a type " << typeid(a).name() << endl;
    cout << "int b[] type " << typeid(b).name() << endl;
    cout << "int (*c)[4] type " << typeid(c).name() << endl;
    cout << "int (&ra)[4] type " << typeid(ra).name() << endl;
    cout << "int d[4] type " << typeid(d).name() << endl;
    return;
}

int main()
{
    int a[4] = {1,2,3,4};
    int (&ra)[4] = a;
    cout << "In main():" << endl;
    cout << "int a[4] type " << typeid(a).name() << endl;
    cout << "int (&ra)[4] type " << typeid(ra).name() << endl;
    fArray(a,a,&a,a,a);
    return 0;
}
g++ 4.4.1结果:
In main():
int a[4] type A4_i
int (&ra)[4] type A4_i
In fArray(...):
int* a type Pi
int b[] type Pi
int (*c)[4] type PA4_i
int (&ra)[4] type A4_i
int d[4] type Pi
main()里面a ra都是int[4]类型
而作为形参int(&ra)[4],int d[4]怎么类型就不一致呢,是否语义不一致?

水木清华jasss回答如下,仔细重看了标准相关内容,确实如此。

Because we have a standard array-to-pointer

conversion here, and here the argument

 

int d[4]

 

is same as

 

int *d

 

, and the array size 4 is meaningless here.

 

For int (&ra)[4], here ra is a reference to

an array with 4 int element, array a is <br /><ul><li></li></ul><br /><br /><div class="zemanta-pixie"><img class="zemanta-pixie-img" alt="" src="http://img.zemanta.com/pixy.gif?x-id=187432ac-8829-830d-adaf-928cb9997ed7" /></div>

bound to ra directly.

 

 

: 这不会导致int a[4]和int d[4]存在语义不一致吗?

 

The two function arguments are different...

 

For ra, the size information is part of the type

and d is merely a pointer.

 

For example, changing arguemnt ra to "int (&ra)[5]"

then the program won't compile, while the compiler

does not care even you replacing "int d[4]" with

"int d[5]".