![](/img/trans.png)
[英]Why is it that the second code gives the desired result while the first doesn't?
[英]Why is it that the second code works while the first one doesnt?
我知道,为了使第一个程序正常工作,我需要通过引用传递a和b,但是在第二个代码中,即使我在所有给定函数中按值传递数组,我也可以获得所需的输出。 这是为什么? 如果我可以按值传递数组,为什么不在第一个程序中使用变量?
我曾尝试在stackoverflow和其他网站上寻找答案,但无法获得能够回答我问题的特定答案。
//FIRST PROGRAM
#include<iostream>
using namespace std;
int swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main() {
int x=5,y=6;
swap(x,y);
cout<<x<<y;
}
//SECOND PROGRAM
#include<iostream>
/*Function to return max sum such that no two elements
are adjacent */
int FindMaxSum(int arr[], int n)
{
int incl = arr[0];
int excl = 0;
int excl_new;
int i;
for (i = 1; i < n; i++)
{
/* current max excluding i */
excl_new = (incl > excl)? incl: excl;
/* current max including i */
incl = excl + arr[i];
excl = excl_new;
}
/* return max of incl and excl */
return ((incl > excl)? incl : excl);
}
/* Driver program to test above function */
int main()
{
int arr[] = {5,200,199,2};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<FindMaxSum(arr, n);
return 0;
}
在第二种情况下传递arr
时,不是按值传递整个数组,而是按值传递指向第一个元素的指针。
您可以通过指针算术和指针引用来修改函数中的数组。 显然,您不能在第一个代码段中做到这一点。
C在允许您使用函数参数列表中的int arr[]
表示法方面很有帮助,但实际上它是int* arr
。 呼叫站点的arr
会衰减为指针类型。
该指针衰减发生在大多数涉及数组的操作中。 sizeof
是一个重要的例外,这就是为什么您可以在调用函数中使用习惯用法sizeof(arr) / sizeof(arr[0])
的原因。 但是请注意,由于指针衰减,通常这会为您提供不同的FindMaxSum
结果。
这归结为C样式数组被视为指针的事实。 void foo(int[])
和void foo(int*)
是C中的等效声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.