指向數組的指針作為函數參數

[英]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...

它有效。我在第一個定義中缺少什么?我以為這兩個是等價的......

3 个解决方案

#1


13  

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). Put differently, the typedef sort of comes with its own parentheses.

你可以使用typedef免費獲得這個(因為它已經是一個類型,*具有不同的含義)。換句話說,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%的情況下,有人使用指向數組的指針,他們可以而且實際上應該只使用指向第一個元素的指針。

#2


2  

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.

那將評估第一個是一個指針數組。第二個是指向固定大小數組的指針。

#3


0  

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.

數組衰減到指針。所以,它適用於第二種情況。在第一種情況下,函數參數是一個指針數組,但不是一個指向序列中第一個元素的整數的指針。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/03/16/72573b9f72f0a693e723e06ae0782c35.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com