问题描述
int (*arr)[5]
表示 arr
是一个指向 5 个整数的数组的指针.现在这个指针到底是什么?
int (*arr)[5]
means arr
is a pointer-to-an-array of 5 integers. Now what exactly is this pointer?
如果我声明 int arr[5]
是否相同,其中 arr
是指向第一个元素的指针?
Is it the same if I declare int arr[5]
where arr
is the pointer to the first element?
两个示例中的 arr
是否相同?如果不是,那么究竟什么是指向数组的指针?
Is arr
from both example are same? If not, then what exactly is a pointer-to-an-array?
推荐答案
在运行时,指针只是一个指针",不管它指向什么,区别是语义上的;与指向元素的指针相比,指向数组的指针传达了不同的含义(对编译器而言)
At runtime, a pointer is a "just a pointer" regardless of what it points to, the difference is a semantic one; pointer-to-array conveys a different meaning (to the compiler) compared with pointer-to-element
处理指向数组的指针时,您指向的是指定大小的数组 - 编译器将确保您只能指向该大小的数组.
When dealing with a pointer-to-array, you are pointing to an array of a specified size - and the compiler will ensure that you can only point-to an array of that size.
即这段代码会编译
int theArray[5];
int (*ptrToArray)[5];
ptrToArray = &theArray; // OK
但这会中断:
int anotherArray[10];
int (*ptrToArray)[5];
ptrToArray = &anotherArray; // ERROR!
处理元素指针时,您可以指向内存中具有匹配类型的任何对象.(它甚至不一定需要在数组中;编译器不会做出任何假设或以任何方式限制您)
When dealing with a pointer-to-element, you may point to any object in memory with a matching type. (It doesn't necessarily even need to be in an array; the compiler will not make any assumptions or restrict you in any way)
即
int theArray[5];
int* ptrToElement = &theArray[0]; // OK - Pointer-to element 0
还有……
int anotherArray[10];
int* ptrToElement = &anotherArray[0]; // Also OK!
总而言之,数据类型int*
并不意味着任何数组知识,但是数据类型int(*)[5]
意味着一个数组,它必须正好包含 5 个元素.
In summary, the data type int*
does not imply any knowledge of an array, however the data type int (*)[5]
implies an array, which must contain exactly 5 elements.
这篇关于指向数组的指针和指向数组第一个元素的指针之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!