johnny68
johnny68

Reputation: 431

Value of array changes while copying to another array

My objective is to create a pulse mode modulation program that would accept the amplitude and time period , and change it to binary.
I looked into this problem, found i was using a local variable in a function so it was going out of scope, changed the code but the problem persists. The 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 I print the array y, the value changes. i followed this link and the rest I don't remember but their answer was also the same.

Upvotes: 0

Views: 113

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

The problem is this:

*y = *x;

The issue is that arrays cannot be copied using =. A function has to be called to do this work, whether it is std::copy, memcpy, your own for loop, etc.

To alleviate this, you could use std::array instead of regular arrays, and with minimal changes to the code, since std::array overloads operator = so that the copy can be done using a more "natural" syntax.

If x and y are

std::array<double, SAMPLE_SIZE>

then the copying is simply:

y = x;

Live Example using std::array

Note that there are issues with calculations and uninitialized variable usage that are out-of-scope of the given issue of array copying. Those issues you will need to resolve.

Upvotes: 1

Related Questions