c++ - Value of array changes while copying to another array -


my objective create pulse mode modulation program accept amplitude , time period , , change binary.
looked problem, found using local variable in function going out of scope, changed code problem persists. code :

#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; } } 

the output :: enter amplitude: 23
enter time: 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

when print array y, value changes. followed this link , rest don't remember answer same.

the problem this:

*y = *x; 

the issue arrays cannot copied using =. function has called work, whether std::copy, memcpy, own for loop, etc.

to alleviate this, use std::array instead of regular arrays, , minimal changes code, since std::array overloads operator = copy can done using more "natural" syntax.

if x , y

std::array<double, sample_size>

then copying simply:

y = x;

live example using std::array

note there issues calculations , uninitialized variable usage out-of-scope of given issue of array copying. issues need resolve.


Comments