为什么不能使用指针的指针作为参数来声明一个函数接收数组的指针 [英] Why cannot use pointer of pointer as parameter to declare a function receive pointer of array

查看:245
本文介绍了为什么不能使用指针的指针作为参数来声明一个函数接收数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c函数,该函数接收数组的指针作为其一个参数.

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 be a pointer of pointer.

int arr[]={0,1,2,3};
int main(){
    receiveArray(arr);
    receiveArrayPtr(&arr);
}
int receiveArray(int *arrPara){....}
int receiveArrayPtr(int **arrPtrPara){....} //Why cannot do this?

错误消息是

"预期为"int **",但参数的类型为"int()[4]"
void receiveArrayPtr(int *
);"

"expected ‘int **’ but argument is of type ‘int ()[4]’
void receiveArrayPtr(int*
);"

想知道为什么

推荐答案

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

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

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

这篇关于为什么不能使用指针的指针作为参数来声明一个函数接收数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆