-3

I am passing array elements to a function. This function adds 5 to each element of the array. I am also passing an integer and adding 5 to it... Even though it is a 'call by value' function the value of the integer dosn't change in main() (which is expected) but the array elements do change...

I wan't to know how and why?

#include <iostream>

using namespace std;

void change(int x[],int y);

int main()
{
    int sharan[]={1,2,3,4};
    int a=10;
    change(sharan,a);
    for(int j=0;j<4;j++)
    {
        cout<<sharan[j]<<endl;
    }
    cout<<endl<<"a is : "<<a;
    return(0);
}

void change(int x[],int y)
{
    for(int i=0;i<4;i++)
    {
        x[i]+=5;
    }
    y+=5;
}
4

3 回答 3

5

数组衰减为指针,

void change(int x[],int y)相当于void change (int *x, int y )

x[i] += 5;

您正在更改地址的内容x+i

y=5;inside基本上更新其地址未传递change的本地副本,因此after的实际值没有修改存在yychange

于 2014-10-02T07:30:28.507 回答
1

因为array始终是引用类型,所以外部的任何更改也会影响arrayin 调用函数。

正如您在代码中看到的:

change(sharan,a); // here `sharan` points the base address an you are passing it.
于 2014-10-02T07:30:32.780 回答
1

C++ 不支持按值传递原始数组。当您尝试这样传递它们时,它们将转换为指向数组的指针。因此,如果您修改数组的元素,那么更改将反映在调用函数中。在这种情况下main()

于 2014-10-02T07:40:04.683 回答