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);
}输出
Actual size of array is : 40 New size of array by passing the value : 8 New size of array by passing the pointer : 8
现在,我们将了解如何在C++中防止数组衰减。有以下两种方法可以防止数组衰减。
- 通过将数组的大小作为参数传递来防止数组衰减,并且不要对数组的参数使用sizeof()。
- 通过引用将数组传递给函数。这可以防止数组转换为指针,并防止数组衰减。
示例
#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);
}输出
Actual size of array is: 40 New size of array by passing reference: 40
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP