[英]Modifying a pointer to an array in a function
I have a problem with passing an array to a function and then modifying it. 我有一个问题,将数组传递给函数,然后修改它。 For example: 例如:
void foo(int ** a) {
int * b = new int[3]
//Initialize b, i.e b = {3, 2, 1}
a = &b;
//*a = {3, 2, 1}
}
int * c = new int[3]
//Initialize c; c = {1, 2, 3}
foo(&c);
// c is still {1, 2, 3}. Why?
I'm not really sure why c
doesn't point to the same array as b
. 我不太确定为什么c
不指向与b
相同的数组。
a
has type int**
and it's passed by value, so modifying it does not modify c
. a
具有类型int**
并且它是按值传递的,因此修改它不会修改c
。
To modify it, you have to do this: 要修改它,您必须这样做:
*a = b;
By doing this, you assign the address of b
to the variable pointed by *a
(which corresponds to c
), so they will point to the same array. 通过这样做,您将b
的地址分配给*a
指向的变量(对应于c
),因此它们将指向同一个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.