Trouble with array

Hello!

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:

40

440
880
1320
1760
2200
2640
3080
3520
3960
4400
4840
5280
5720
6160
6600
7040
7480
7920
8360
8800
0
0
0
2200
4400
6600
8800
0
9216
1
-6144
3
0
0
-15104
-15360
-16384
-16128
-15872
-14848

Hope someone is able to help, as it is driving me mad, and is a part of an assignment to be delivered very soon.

Thank you :slight_smile:

sizeof() returns the number of bytes used, not the number of elements.

You can divide that value by the size of a single element to get the number of elements.

 sizeof(myArray)

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

That makes sense! Now, for some reason, when I iterate through it says the size of the array is 2. My code looks like this:

Serial.println(sizeof(myArray[0]);
for (int e = 0; e < sizeof(myArray[0]); e++) {
. Serial.println(myArray[e]);
}

Gives the following output

2
440
880

sizeof(myArray[0])
Yes, that will be 2

Read my previous reply more carefully

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

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.