为什么在此函数调用后数组会更改?
Why is the array changed after this function call?
在下面的程序中,数组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
正确的输出
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- C++ 2D 数组在调用附近的小区时循环到行中的第一个单元
- 在数组函数指针中调用void
- 为什么当数组作为调用方函数中的参数传递时,不能在被调用函数中使用 foreach 循环打印数组的值
- 在C++中传递结构数组 - 被调用函数中不存在结构元素,如何正确传递向量?
- 为什么我不能从铸造的字节(char)数组中调用虚拟函数
- C 从功能数组中调用函数
- 在对象指针数组上调用函数
- 如何在数组中调用函数
- 无法使用数组程序调用布尔函数
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- C++:为什么在声明对象数组时调用构造函数
- 在C++中,当继承一个类并重写一个函数时.从数组中调用那个被重写的函数时,我得到了一个意外的结果
- 为作为类成员的对象数组立即调用的构造函数
- 为什么当我创建一个对象数组时调用默认构造函数,但当我将obj创建为简单变量时却出错
- 使用数组索引调用函数
- C++在派生类指针数组上调用虚拟函数
- C++用不同的输入(数组)调用相同的函数,我如何收缩我的语句