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

Submitted by Violet on Thu, 09/27/2018 - 11:57

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.

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

  Joined August 16, 2016      998
Tuesday at 12:29 AM

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!

  Joined August 16, 2018      42
Thursday at 11:31 AM

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

 

  Joined August 16, 2016      998
Tuesday at 12:29 AM

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. 

  Joined August 16, 2018      42
Thursday at 11:31 AM