什么是C++中的数组衰减(如何预防?)

什么是数组衰减?
【什么是C++中的数组衰减(如何预防?)】数组类型和维数的损失称为数组的衰减, 通常发生在我们通过值或指针将数组传递给函数时。它的作用是, 将第一个地址发送到作为指针的数组, 因此数组的大小不是原始的, 而是指针在内存中占用的大小。

//C++ code to demonstrate array decay #include< iostream> using namespace std; //Driver function to show Array decay //Passing array by value void aDecay( int *p) { //Printing size of pointer cout < < "Modified size of array is by " " passing by value: " ; cout < < sizeof (p) < < endl; }//Function to show that array decay happens //even if we use pointer void pDecay( int (*p)[7]) { //Printing size of array cout < < "Modified size of array by " "passing by pointer: " ; cout < < sizeof (p) < < endl; }int main() { int a[7] = {1, 2, 3, 4, 5, 6, 7, }; //Printing original size of array cout < < "Actual size of array is: " ; cout < < sizeof (a) < < endl; //Calling function by value aDecay(a); //Calling function by pointer pDecay(& a); return 0; }

输出如下:
Actual size of array is: 28 Modified size of array by passing by value: 8 Modified size of array by passing by pointer: 8

在上面的代码中, 实际的数组具有7个int元素, 因此具有28个大小。但是通过按值和指针调用, 数组衰减为指针并输出1个指针的大小, 即8(32位中的4)。
如何防止数组衰减?
处理衰减的典型解决方案是将数组大小也作为参数传递, 而不对数组参数使用sizeof
防止数组衰减的另一种方法是通过引用将数组发送到函数中。这样可以防止将数组转换为指针, 从而防止衰减。
//C++ code to demonstrate prevention of //decay of array #include< iostream> using namespace std; //A function that prevents Array decay //by passing array by reference void fun( int (& p)[7]) { //Printing size of array cout < < "Modified size of array by " "passing by reference: " ; cout < < sizeof (p) < < endl; }int main() { int a[7] = {1, 2, 3, 4, 5, 6, 7, }; //Printing original size of array cout < < "Actual size of array is: " ; cout < < sizeof (a) < < endl; //Calling function by reference fun(a); return 0; }

输出如下:
Actual size of array is: 28 Modified size of array by passing by reference: 28

在上面的代码中, 按引用传递数组解决了数组衰减的问题。两种情况下的尺寸均为28。
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

    推荐阅读