问题
I have a 2D array of pointer
main.c
Int32 * pRxSeqAddr[2][2];
func(pRxSeqAddr);
/
func.c
void func( Int32** pRxSeqAddrPtr)
{
///
}
I get this error:
argument of type "Int32 *(*)[2]" is incompatible with parameter of type "Int32 **
I know if it was 1D array of pointer then this function call is fine, but 2D is nagging me..
please help
回答1:
Change func.c to:
void func(Int32 *pRxSeqAddrPtr[][2])
{
}
In general, to pass 2D arrays to functions you need to specify the array dimensions for all but the first dimension, so in this example you need the [2] for the last dimension but you can optionally omit it for the first dimension, i.e.
void func(Int32 *pRxSeqAddrPtr[2][2])
{
}
would also be valid, but somewhat redundant.
回答2:
Except when it is the operand of the sizeof
or unary &
operators or is a string literal being used to initialize another array, an expression of type "N-element array of T" will be implicitly converted ("decay") to type "pointer to T", and its value will be the address of the first element of the array.
When you make the call to func(pRxSeqAddress)
, the type of the expression pRxSeqAddress
is converted from "2-element array of 2-element array of pointer to Int32" to "pointer to 2-element array of pointer to Int32", or Int32 *(*)[2]
. Thus, the prototype for func
should be
void func(Int32 *(*pRxSeqAddressPtr)[2]) { ... }
In the context of a function parameter declaration, T a[]
and T a[N]
are both synonymous with T *a
; a
is actually of pointer type, not an array type. So the above could be rewritten as
void func(Int32 *pRxSeqAddressPtr[][2]) { ... }
which looks a little cleaner than the pointer to array syntax; however, I prefer the former as it describes exactly what's going on. Note that this is only true in the context of a function parameter declaration.
So, given the declaration T a[N][M];
, the following all hold true
Expression Type Decays to ---------- ---- --------- a T [N][M] T (*)[M] &a T (*)[N][M] n/a *a T [M] T * a[i] T [M] T * &a[i] T (*)[M] n/a *a[i] T n/a a[i][j] T n/a
Note that it's the type of the expression referring to the array that changes, not the array itself; the object pRxSeqAddr
defined in main
is always and forever of array type.
回答3:
This will surely work:
Int32* pRxSeqAddr[2*2];
func(pRxSeqAddr);
void func(Int32** pRxSeqAddrPtr){};
Or, in your original example, you could call the function with
funct( &pRxSeqAddr[0][0] );
回答4:
In C, by default, 2D array'' are
array of pointers to 1D arrays''.
So, there, you have to name your type : Int32***
First star for the first array dimension. (arrays are pointer to their first item) Second star for the second array dimension. (pointers to first item of the line) Third star because the items are pointers.
来源:https://stackoverflow.com/questions/4152837/passing-2d-array-of-pointer-to-function-c