[英]Pointer to array as function parameter
I wrote a function which takes a pointer to an array to initialize its values: 我写了一个函数,它接受一个指向数组的指针来初始化它的值:
#define FIXED_SIZE 256
int Foo(int *pArray[FIXED_SIZE])
{
/*...*/
}
//Call:
int array[FIXED_SIZE];
Foo(&array);
And it doesn't compile: 它不编译:
error C2664: 'Foo' : cannot convert parameter 1 from 'int (*__w64 )[256]' to 'int *[]'
错误C2664:'Foo':无法将参数1从'int(* __ w64)[256]'转换为'int * []'
However, I hacked this together: 但是,我一起攻击了这个:
typedef int FixedArray[FIXED_SIZE];
int Foo(FixedArray *pArray)
{
/*...*/
}
//Call:
FixedArray array;
Foo(&array);
And it works. 它有效。 What am I missing in the first definition?
我在第一个定义中缺少什么? I thought the two would be equivalent...
我以为这两个是等价的......
int Foo(int *pArray[FIXED_SIZE])
{
/*...*/
}
In the first case, pArray
is an array of pointers, not a pointer to an array . 在第一种情况下,
pArray
是一个指针数组,而不是指向数组的指针 。
You need parentheses to use a pointer to an array: 您需要括号来使用指向数组的指针:
int Foo(int (*pArray)[FIXED_SIZE])
You get this for free with the typedef
(since it's already a type, the *
has a different meaning). 你可以使用
typedef
免费获得这个(因为它已经是一个类型, *
具有不同的含义)。 Put differently, the typedef
sort of comes with its own parentheses. 换句话说,
typedef
类型带有自己的括号。
Note: experience shows that in 99% of the cases where someone uses a pointer to an array, they could and should actually just use a pointer to the first element . 注意:经验表明,在99%的人使用指向数组的指针的情况下, 他们可以而且实际上应该只使用指向第一个元素的指针 。
One simple thing is to remember the clockwise-spiral rule which can be found at http://c-faq.com/decl/spiral.anderson.html 一个简单的事情是记住顺时针螺旋规则,可以在http://c-faq.com/decl/spiral.anderson.html找到。
That would evaluate the first one to be an array of pointers . 这将评估第一个是一个指针数组。 The second is pointer to array of fixed size.
第二个是指向固定大小数组的指针。
An array decays to a pointer. 数组衰减到指针。 So, it works in the second case.
所以,它适用于第二种情况。 While in the first case, the function parameter is an array of pointers but not a pointer to integer pointing to the first element in the sequence.
在第一种情况下,函数参数是指针数组,但不是指向序列中第一个元素的整数的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.