开发者

passing array on the heap and on the stack to function

开发者 https://www.devze.com 2023-03-11 04:43 出处:网络
I have a simple c++ question concerning passing an array to a function foo(). Assume I have two arrays A and B:

I have a simple c++ question concerning passing an array to a function foo(). Assume I have two arrays A and B:

double* A=new double[3];

and

double B[3];

When I pass both开发者_StackOverflow社区 to the function

foo(double* A; double *B)

which is intended to manipulates both arrays. However by executing

foo(A,B)

foo is acting on a copy of A and only the changes to B remain when leaving foo(). This is not the case if foo is defined as

foo(double* &A; double *B).

My question: Why is a copy of a created although I pass the address of A like double* A (as in the case of B) in the first example of foo()?


foo is acting on a copy of A and only the changes to B remain when leaving foo().

What exactly are you doing inside of foo? Changes to the objects themself should be visible outside of foo in both cases. If you are trying to change the value of pointer A, it won't be visible outside of foo - a copy of the pointer is passed to the function, but of course it still points to the same array.


If you want to pass an array reference to a function you have to use a double pointer reference:

foo(double** A, double **B);

double** A=new complex<double>[3];
0

精彩评论

暂无评论...
验证码 换一张
取 消