[英]copying array modifies behaviour of function using the original array
So I have this small code: 所以我有这个小代码:
extern "C"{
void foo(int* nR,int* mR,float* x,float* out){ //&&
const int n=*nR,m=*mR;
other_foo(n,m,x,out);
}
}
that works fine. 效果很好。 But now I want to copy the
n-array
of float
x
before passing it to the function other_foo
(since other_foo
will be altering x
and I want to keep a copy). 但是现在我想在将
float
x
的n-array
传递给函数other_foo
之前复制它(因为other_foo
将更改x
且我想保留一个副本)。
if I do like so, all works fine: 如果我喜欢,一切正常:
extern "C"{
void foo(int* nR,int* mR,float* x,float* out){ //&&
const int n=*nR,m=*mR;
float y[n];
for(int i=0;i<n;i++) y[i]=x[i];
other_foo(n,m,x,out);
}
}
but if I do like so: 但是如果我喜欢这样:
extern "C"{
void foo(int* nR,int* mR,float* x,float* out){ //&&
const int n=*nR,m=*mR;
float y[n];
std::copy(x,x+n,y);
other_foo(n,m,x,out);
}
}
all hell breaks lose: the output of other_foo
is not the same anymore! 所有的地狱都输了:
other_foo
的输出不再相同!
My question is, of course, why? 我的问题当然是为什么?
There is no difference between these two code snippets relative to the result of copying. 相对于复制结果,这两个代码段之间没有区别。
void foo(int* nR,int* mR,float* x,float* out){ //&&
const int n=*nR,m=*mR;
float y[n];
for(int i=0;i<n;i++) y[i]=x[i];
other_foo(n,m,x,out);
}
void foo(int* nR,int* mR,float* x,float* out){ //&&
const int n=*nR,m=*mR;
float y[n];
std::copy(x,x+n,y);
other_foo(n,m,x,out);
}
The both copy n elements from x to y. 两者都将n元素从x复制到y。
However this code is not C++ compliant. 但是,此代码不符合C ++。 The size of an array shall be a constant expression known at compile time.
数组的大小应为在编译时已知的常数表达式。 So it would be more correctly to allocate the array dynamically.
因此,动态分配数组会更正确。
For example 例如
void foo(int* nR,int* mR,float* x,float* out){ //&&
int n = *nR, m = *mR;
float *y = new float[n];
std::copy( x, x+n, y );
other_foo( n, m, x, out );
// other code maybe including delete [] y
}
I think that the problem is not in this function. 我认为问题不在于此功能。 It seems that the problem is in called function other_foo
看来问题出在所谓的函数other_foo中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.