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

传送门 ==>> AutoSAR实战系列300讲「糖果Autosar」总目录

1 什么是数组衰减?

数组类型和维度的丢失称为数组衰减。这通常发生在我们通过值或指针将数组传递给函数时。它所做的是,它将数组第一个元素地址作为指针发送给的,因此数组的大小不是原始的,而是指针在内存中占用的大小。

2 数组衰减的示例

// 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;
  
    // Passing a pointer to array
    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 个)。

3 如何防止数组衰减?

处理衰减的典型解决方案是将数组的大小也作为参数传递;防止数组衰减的另一种方法是通过引用将数组发送到函数中。这可以防止将数组转换为指针,从而防止衰减。

// 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。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖果Autosar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值