Why cannot use pointer of pointer as parameter to declare a function receive pointer of array

后端 未结 2 1128
攒了一身酷
攒了一身酷 2021-01-24 17:03

I have a c function receiving pointer of array as its one parameter.

Since pass an array is actually the pointer of its first element, so the pointer of an array should

相关标签:
2条回答
  • 2021-01-24 17:47

    Since pass an array is actually the pointer of its first element, so the pointer of an array should be a pointer of pointer.

    That's not how it works.

    Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

    The type of the expression arr in the call to receiveArray is "4-element array of int". Since it is not the operand of the sizeof or unary & operators, it is converted to an expression of type int *, which is what the function receives.

    In the call to receiveArrayPtr, the expression arr is the operand of the unary & operator, so the conversion rule doesn't apply; the type of the expression &arr is "pointer to 4-element array of int", or int (*)[4].

    This conversion is called array name decay.

    0 讨论(0)
  • 2021-01-24 17:59

    so the pointer of an array should be a pointer of pointer.

    No. Arrays are not pointers. Pointer to pointer and pointer to array both are of different types.

    &arr is of type int (*)[4]. You are passing an argument of type pointer to an array of 4 int while your function expects argument of type int **.

    Change the function declaration to

    int receiveArrayPtr(int (*arrPtrPara)[4])
    
    0 讨论(0)
提交回复
热议问题