为什么在此函数调用后数组会更改?

Why is the array changed after this function call?

本文关键字:数组 函数调用 为什么      更新时间:2023-10-16

在下面的程序中,数组x的第一个元素的值在将数组作为参数传递给某个修改其参数的函数后打印为零。int变量y不会发生同样的情况,另一个函数中的修改在调用函数中不会被注意到。因此,我希望数组在函数调用之前保留其值,就像y一样。为什么数组会更改而变量不会更改?

void func1 (int x[]){
x[0]=0;
}
void func2(int y){
y=0;
}
int main(){
int x[]={7}, y=8;
func1(x);
func2(y);
cout << x[0] << y;
return 0;
}

输出:

08

预期:

78

参数int[]int*完全相同,一个指向整数的指针。传递给函数的数组衰减到指向数组第一个元素的指针,从而通过下标运算符取消引用它并修改 int pointee 会导致原始元素被修改。

供您参考,我将值放在每行前面的注释中

void func1 (int x[]){
x[0]=0;//x here has same address as in main function so changes can be //directly apply to the original value of x array
//x[0]=7 was passed in this function is now modified by have a value x[0]=0
} 
void func2(int y){
y=0;//but y is a different variable in this function it is not the same y in main function so if you change its value it does not mean that you are changing the value of y in main function so it does not give you the expected output
// it is due to local variable concept y in func2 is different and y in main is a different so all you have to do is to pass address of y variable so that if you want to change any thing is y will directly change its value in main function
}
int main(){
int x[]={7}, y=8;
func1(x);
func2(y);
cout << x[0] << y;
return 0;
}

数组使用连续的内存位置来存储数据。 当你调用func1(int x[])时,前一个值会随着函数给出的值而变化,并且位置保持不变,所以
在 main 函数中

x[0]=7

函数调用后

x[0]=0   

这就是数组值更改的原因。
对于变量,您没有返回任何内容,这就是它没有更改的原因。 所以在这种情况下08正确的输出