数组的值在复制到另一个数组时发生更改
Value of array changes while copying to another array
我的目标是创建一个脉冲模式调制程序,接受振幅和时间周期,并将其更改为二进制
我研究了这个问题,发现我在函数中使用了一个局部变量,所以它超出了范围,更改了代码,但问题仍然存在。代码:
#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::copy
、memcpy
、您自己的for
循环等。
为了缓解这种情况,您可以使用std::array
而不是常规数组,并且对代码的更改最小,因为std::array
重载operator =
,因此可以使用更"自然"的语法进行复制。
如果x
和y
是
std::array<double, SAMPLE_SIZE>
那么复制就是:
y = x;
使用std::array 的实际示例
请注意,存在计算和未初始化变量使用方面的问题,这些问题超出了给定的数组复制问题的范围。那些你需要解决的问题。
相关文章:
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 将字符数组复制到 QByte 数组中,而无需传递指针
- std::transform 将一个结构数组复制到另一个结构数组
- 如何使用指针C++将元素从2D数组复制到1D数组
- 如何将 int4 数组复制到 int8 向量中
- 如何将多维字符数组复制到字符 * 中
- std::将三维数组复制到三维向量中
- 为什么我不能将 C 样式数组复制到 std::array?
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 为什么当我想将(使用 memcpy)结构数组复制到字符数组时,字符数组为空
- 如何将数据从数组复制到C++特征矩阵或向量
- 将数组复制C++作为特征矩阵的向量
- 如何在 c++ 中将数组复制到文件
- 如何将对象数组作为构造函数中的参数传递,然后将传递的数组复制到另一个数组(仍在构造函数中)
- CUDA 将大于线程计数的数组复制到共享内存
- 可以使用 std::copy 将 3D 数组复制到矢量
- 如何在C++中将本地字符串数组复制到私有成员字符串数组
- 如何使用 std::copy 将一个 constexpr 数组复制到另一个 constexpr 数组
- 如何将 char 类型数组传递给函数并将第一个字符数组复制到第二个图表数组并使用 c++ 进行比较