指向数组的指针与指向数组的第一个元素的指针之间的区别 [英] difference between pointer to an array and pointer to the first element of an array

查看:311
本文介绍了指向数组的指针与指向数组的第一个元素的指针之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于指向数组的指针与指向数组的第一个元素的指针之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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