且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不能使用指针的指针作为参数来声明一个函数接收数组的指针

更新时间:2022-12-13 15:07:28

由于传递数组实际上是其第一个元素的指针,因此数组的指针应该是指针的指针.

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.

除非它是sizeof或一元&运算符的操作数,或者是用于初始化声明中另一个数组的字符串文字,否则类型为"N-element"的表达式数组T"将被转换为类型为指向T的指针"的表达式,该表达式的值将为数组第一个元素的地址.

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.

receiveArray的调用中表达式arr的类型为"int的4元素数组".由于它不是sizeof运算符或一元&运算符的 not 运算符,因此将其转换为函数接收的类型为int *的表达式.

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.

在对receiveArrayPtr的调用中,表达式arr是一元&运算符的操作数,因此转换规则不适用.表达式&arr的类型是指向int的4元素数组的指针"或int (*)[4].

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

此转换称为数组名称衰减.