& 什么类型?返回 C 函数内的数组参数?
当将数组参数传递给函数时,它的内存地址被复制到数组参数中。因此:
sizeof()
返回数组参数的整个数组的大小(在调用者内部)sizeof()
返回数组参数的指针的大小(内部称为函数)
我的问题是,函数内部的数组参数是什么类型?更具体地说,在数组参数上使用 & 运算符时返回什么类型?它不是指向类型数组的指针,也不是指向类型的指针,如以下代码所示(标记为BAD):
void doSomething(int arrayParam[10]);
int main()
{
int array[10] = { 0 };
int (*arrayPtr)[] = &array; // OK
printf("%p\n", array); // 0x7fff5fbff790
doSomething(array);
return 0;
}
void doSomething(int arrayParam[10])
{
printf("%p\n", arrayParam); // 0x7fff5fbff790
int (*arrayPtr)[] = &arrayParam; // BAD: Initialization from incompatible pointer type
int * element0Ptr = &arrayParam; // BAD: Initialization from incompatible pointer type
element0Ptr = arrayParam; // OK
element0Ptr = &arrayParam[0]; // OK
}
感谢您提供的任何帮助! :)
When passing an Array Argument to a Function, it's memory address is copied into an Array Parameter. Because of this:
sizeof()
returns the size of the entire array for the Array Argument (inside caller)sizeof()
returns the size of a pointer for the Array Parameter (inside called Function)
My question is, what type is the Array Parameter inside the Function? And more specifically, what type is returned when using the & Operator on an Array Parameter? It's not a Pointer to Array of Type, nor is it a Pointer to Type, as shown in this code (labeled BAD):
void doSomething(int arrayParam[10]);
int main()
{
int array[10] = { 0 };
int (*arrayPtr)[] = &array; // OK
printf("%p\n", array); // 0x7fff5fbff790
doSomething(array);
return 0;
}
void doSomething(int arrayParam[10])
{
printf("%p\n", arrayParam); // 0x7fff5fbff790
int (*arrayPtr)[] = &arrayParam; // BAD: Initialization from incompatible pointer type
int * element0Ptr = &arrayParam; // BAD: Initialization from incompatible pointer type
element0Ptr = arrayParam; // OK
element0Ptr = &arrayParam[0]; // OK
}
Thanks for any help you can offer! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
大多数时候,当您使用数组时,它会衰减为指向其初始元素的指针。因此,如果您有:
f()
获取指向array
的初始元素的指针。一开始相当令人困惑的是,如果一个函数有一个数组类型的参数(就像你有
void f(int x[])
),它实际上会被转换,这样它与void f(int* x)
完全相同。它们之间没有区别:数组类型参数与指针类型参数相同。将数组传递给函数后,您所拥有的只是一个指向其初始元素的指针,因此如果将
&
运算符应用于int*
,您会得到一个int**
(指向int*
的指针)。Most of the time, when you use an array, it decays to a pointer to its initial element. So, if you have:
f()
gets a pointer to the initial element ofarray
.Something that is rather confusing at first is that if a function has a parameter that is of an array type (like if you had
void f(int x[])
), this is actually converted such that it is exactly the same asvoid f(int* x)
. There is no difference between them: array type parameters are the same as pointer type parameters.Once you pass an array to a function, all you have is a pointer to its initial element, so if you apply the
&
operator to theint*
, you get anint**
(a pointer to anint*
).