什么是C ++中的阵列衰减?
数组类型和尺寸的损失称为数组衰减。当我们通过指针或值将数组传递给函数时,就会发生这种情况。第一个地址发送到作为指针的数组。这就是为什么数组的大小不是原始大小。
这是C++语言中数组衰减的示例,
示例
#include<iostream>
using namespace std;
void DisplayValue(int *p) {
cout << "New size of array by passing the value : ";
cout << sizeof(p) << endl;
}
void DisplayPointer(int (*p)[10]) {
cout << "New size of array by passing the pointer : ";
cout << sizeof(p) << endl;
}
int main() {
int arr[10] = {1, 2, };
cout << "Actual size of array is : ";
cout << sizeof(arr) <endl;
DisplayValue(arr);
DisplayPointer(&arr);
return 0;
}输出结果
Actual size of array is : 40 New size of array by passing the value : 8 New size of array by passing the pointer : 8
防止数组衰减
有以下两种防止数组衰减的方法。
通过将数组的大小作为参数传递,可以防止数组衰减,并且不要在数组的参数上使用sizeof()数组。
通过引用将数组传递给函数。它防止将数组转换为指针,并防止数组衰减。
这是防止C++语言中的数组衰减的示例,
示例
#include<iostream>
using namespace std;
void Display(int (&p)[10]) {
cout << "New size of array by passing reference: ";
cout << sizeof(p) << endl;
}
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "Actual size of array is: ";
cout << sizeof(arr) <<endl;
Display(arr);
return 0;
}输出结果
Actual size of array is: 40 New size of array by passing reference: 40
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短