Problem with copying array with Arduino (memcpy()) - affects other variables

Violet's picture

Offline

Joined: Aug 16, 2018

Replies: 29
Problem with copying array with Arduino (memcpy()) - affects other variables
September 27, 2018 - 11:57am

Hi,

I have three four sets of array each of varied length. Out of which one is the main array and the remaining three will have only fixed values

int fixed_array_1 [5] = { 5,10,15,20,25};

int fixed_array_2 [4] = {4, 8, 12, 16};

int fixed_array_3 [4] = {3,6,9,12};

int main_array[] = {}

 

Now, inside the program based on few conditions I have to copy either one of these fixed array into my main array. I am using memcpy() to do this something like this

memcpy(main_array, fixed_array_1, 5);

Everything works fine this way except I noticed that few of my global variables are getting some random values. It took a lot of time to debug using serial monitor and final found that when I comment this line out the variables work normally.

So now I am sure that this line is the culprit! how to get away with this?

Please help!

Thanks.

Aswinth Raj's picture

Offline

Joined: Aug 16, 2016

Replies: 910
Try for loop instead of memcpy()
September 27, 2018 - 12:13pm

Hi violet,

Problem sounds odd. may be there is a problem with memcpy() function itself did you try replacing the the memcpy() with for loop like this

for (int i=0; i<=3; i++)
     { main_array[i] = fixed_array_1[i]; delay(10);}

Violet's picture

Offline

Joined: Aug 16, 2018

Replies: 29
for loop also does not work
September 27, 2018 - 12:15pm

Hi Aswint,

YES

I tried the for loop as you said still I am having the same problem. When I comment out the for loop it works as expected.

The variables whoes values are getting affected are global variable of integer type.

I also tried them as volatile int and still having the same problem.

Please help mw with this. I am loosing my patients with this!

Aswinth Raj's picture

Offline

Joined: Aug 16, 2016

Replies: 910
Problem with array declaration
September 27, 2018 - 12:18pm

Hi again,

I tired the same program and was able to re-create the problem, but the solution was simple.

The problem is with your array declaration.

int main_array[] = {}

Since we have not specified the size of the array it is creating the problem. For your program the maximum array size is 5.

So change the line to

int main_array[5] = {}

And it works as expected

 

Violet's picture

Offline

Joined: Aug 16, 2018

Replies: 29
Problem solved ;-) Array declaration problem
September 27, 2018 - 12:20pm

Hi 

Thanks a ton, it is working now.

Never expected the problem to be with declaration. I wonder why the former was wrong since it is a valid declaration, also how it affected a random variable in my program. 

Any way  the problem is solved now thanks again.