I'm having some frustrating errors with the Arduino that I can't understand, I'm using a function to build an array. It takes a value, divides it into a given number of equal parts, and puts these parts in the array. My program is supposed to make 20, so I make an array with a set size of 20. Trouble is when I print it directly after making it, the size is 40. The first 20 values in the array are correct, but the other 20 are complete nonsense that I don't understand. Leaving the code below for reference.
int myArray[20];
void buildArray(int totalLength) {
. int piece = totalLength / sizeof(myArray);
. for (int e = 0; e < sizeof(myArray); e++) {
. . myArray[e] = (e + 1) * piece;
. }
}
(Sorry for the ugly code I couldn't find out how to add it here)
Now when I print the size of the array, followed by iterating through this and printing each value in the array I get the following nonsense:
This will return the number of bytes used by the array, not the number of elements in the array. You are using an array of ints, each of which take 2 bytes. Do you see the problem ?
Using this instead
sizeof(myArray) / sizeof(myArray[0])
will give the number of elements for an array of any kind
Ah man sorry my bad haha, makes perfect sense now, thank you very much! Reckon I can get it working now. So these extra numbers they just showed up randomly? In other languages this would throw an index error in this instant right?
The other numbers were whatever was in the memory locations when you read them. Luckily you did not write to then because that may have corrupted other variables