数组的值在复制到另一个数组时发生更改

Value of array changes while copying to another array

本文关键字:数组 复制 另一个      更新时间:2023-10-16

我的目标是创建一个脉冲模式调制程序,接受振幅和时间周期,并将其更改为二进制
我研究了这个问题,发现我在函数中使用了一个局部变量,所以它超出了范围,更改了代码,但问题仍然存在。代码:

#include <iostream>
#include <cmath>
#define SAMPLE_SIZE 12
class sine_curve
{
public:

int get(double amplitude, double time, double *x, double frequency, int sample)
{
    for(sample = 0; sample <= time; sample++)
    {
        x[sample] = amplitude * sin(2 * 3.142 * frequency * sample);
        std::cout << x[sample]<<"t";
    }
    std::cout << std::endl;
return *x;    }
};
int main()
{
double amplitude, time, frequency, x[SAMPLE_SIZE], y[SAMPLE_SIZE];
int sample;
std::cout << "Enter amplitude: ";
std::cin >> amplitude;
std::cout << "Enter time: ";
std::cin >> time;
sine_curve sine;
sine.get(amplitude, time, x, frequency,sample);
for(sample = 0; sample <= time; sample++)
{
    std::cout << x[sample] << std::endl;
}
std::cout << std::endl;
*y = *x;
for(sample = 0; sample <= time; sample++)
{
    std::cout << y[sample] << std::endl;
}
}

输出:输入振幅:23
输入时间:3
0 1.00344e-307 2.00687e-307 3.01031e-307
0
1.00344e-307
2.00687e-307
3.01031e-307

0
2.07377e-317
5.61259e-321
2.12203e-314

打印数组y时,值会发生变化。我关注了这个链接,其他的我不记得了,但他们的答案也是一样的。

问题是:

*y = *x;

问题是无法使用=复制阵列。必须调用一个函数来完成这项工作,无论是std::copymemcpy、您自己的for循环等。

为了缓解这种情况,您可以使用std::array而不是常规数组,并且对代码的更改最小,因为std::array重载operator =,因此可以使用更"自然"的语法进行复制。

如果xy

std::array<double, SAMPLE_SIZE>

那么复制就是:

y = x;

使用std::array 的实际示例

请注意,存在计算和未初始化变量使用方面的问题,这些问题超出了给定的数组复制问题的范围。那些你需要解决的问题。