什么是指针衰减数组

什么是指针衰减数组

本文介绍了什么是指针衰减数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是数组到指针衰减?与数组指针有什么关系吗?

What is array to pointer decay? Is there any relation to array pointers?

推荐答案

据说数组会衰减"为指针.声明为 int numbers [5] 的 C++ 数组不能重新指向,即您不能说 numbers = 0x5a5aff23.更重要的是,衰减一词表示类型和维度的损失;numbers 通过丢失维度信息(计数 5)衰减为 int* 并且类型不再是 int [5].在此处查看不发生衰减的情况.

It's said that arrays "decay" into pointers. A C++ array declared as int numbers [5] cannot be re-pointed, i.e. you can't say numbers = 0x5a5aff23. More importantly the term decay signifies loss of type and dimension; numbers decay into int* by losing the dimension information (count 5) and the type is not int [5] any more. Look here for cases where the decay doesn't happen.

如果你按值传递数组,你真正做的是复制一个指针——指向数组第一个元素的指针被复制到参数(其类型也应该是数组元素类型的指针).由于数组的衰减性质,这是有效的;一旦衰减,sizeof 不再给出完整数组的大小,因为它本质上变成了一个指针.这就是为什么首选(除其他原因外)通过引用或指针传递.

If you're passing an array by value, what you're really doing is copying a pointer - a pointer to the array's first element is copied to the parameter (whose type should also be a pointer the array element's type). This works due to array's decaying nature; once decayed, sizeof no longer gives the complete array's size, because it essentially becomes a pointer. This is why it's preferred (among other reasons) to pass by reference or pointer.

传入数组的三种方式:

void by_value(const T* array)   // const T array[] means the same
void by_pointer(const T (*array)[U])
void by_reference(const T (&array)[U])

最后两个将提供正确的 sizeof 信息,而第一个不会,因为数组参数已经衰减以分配给参数.

The last two will give proper sizeof info, while the first one won't since the array argument has decayed to be assigned to the parameter.

这篇关于什么是指针衰减数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:42