什么是阵列衰减? 阵列类型和尺寸的损失称为阵列衰减。当我们通过值或指针将数组传递给函数时,通常会发生这种情况。它所做的是,它将第一个地址发送到作为指针的数组,因此数组的大小不是原来的大小,而是内存中指针占用的大小。
null
CPP
// 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)。 如何防止阵列衰减? 处理衰减的典型解决方案是将数组的大小也作为参数传递,而不是在数组参数上使用sizeof(请参阅) 这 (详情请参阅) 防止数组衰减的另一种方法是通过引用将数组发送到函数中。这样可以防止数组转换为指针,从而防止衰减。
CPP
// 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。 本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END