c++ - 复制到另一个数组时数组的值发生变化

标签 c++ arrays

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

#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 时,值发生了变化。 我关注了this链接和其他我不记得了,但他们的回答也是一样的。

最佳答案

问题是这样的:

*y = *x;

问题是无法使用 = 复制数组.必须调用一个函数来完成这项工作,无论它是 std::copy , memcpy , 你自己的 for循环等

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

如果xy

std::array<double, SAMPLE_SIZE>

那么复制就是:

y = x;

Live Example using std::array

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

关于c++ - 复制到另一个数组时数组的值发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38509437/

相关文章:

arrays - 结构数组 : How to save in coredata?

javascript - 如何获取稀疏数组中的下一个元素

ios - 从数组中删除特定值而不是使用索引路径删除

c++ - GTK3 检测用户调整窗口大小

c++ - vc++ 中出现运行时错误,但 gcc 中没有

c++ - boost::spirit::qi::parse 语法没有按预期工作

c++ - 参数包是模板参数吗?

c++ - 非模板类中的模板化 friend 类,其中 friend 也使用该类

javascript - 需要使这个对象数组在 javaScript 中可重用

c++ - 数组元素编号