I was doing an assignment, tried simplifying code with same results.
unsigned char x=5;
byte a1[100];
/*byte a1 is then filled*/
byte a2[7];
int counter = 0;
for (counter=0;counter!=8;counter++)
{
a2[counter]=a1[counter];
printf("%d ",x);
}
result is 5 5 5 5 5 5 5 ?
where ? is a random number
i’m confused why this is happening as the arrays do not even relate to this variable, and it seems that everything is in range for arrays. what could be causing this or how can i solve?
You’re writing past the end of the array. Writing to
a2[7]is undefined behaviour (and in your case, it wrote to the variable immediately after the array on the stack).To fix this, either end the loop at 7 or declare
byte a2[8];.