0

I would like to ask about a weirdness in my program. This is my program:

void setup() {
  Serial.begin(9600);
}

void loop() {
   workout_Text();
}

void workout_Text() {
  int woT_x[] = {1, 4, 8, 12, 16};
  int woT_y[] = {1, 4, 8, 12, 16};
  int n = sizeof(woT_y);
  on_led(woT_x, woT_y, n);
}

void on_led(int a_mat[], int b_mat[], int m) {
  for (int i = 0; i < m; i++) {
    Serial.print(a_mat[i]);
    Serial.print(" : ");
    Serial.println(b_mat[i]);
    delay(100);
  }
} 

This is the part of my program for a LED matrix. The on_led purpose function is for printing the value of a_mat and b_mat. Instead of printing:

1 : 1
4 : 4
8 : 8
12 : 12
16 : 16
1 : 1
4 : 4
8 : 8
16 : 16

It prints:

1 : 1
4 : 4
8 : 8
12 : 12
16 : 16
13312 : 1
23296 : 4
1 : 8
4 : 12
8 : 16
1 : 1
4 : 4
8 : 8

Where does the big number come from? I am sure that my code is right to just print the a_mat and b_mat.

Thank you.

2 Answers 2

3

sizeof() returns the total number of bytes. If you have an array of 5 ints, where each int is 2 bytes long, sizeof will return 10.

If you want the number of elements in the array, you need to divide by the size of a single element:

int n = sizeof(woT_y) / sizeof(woT_y[0]);
0
3

sizeof counts bytes. the type of your array is int. sizeof of the int array of length 5 is 10 bytes. your for loop goes to i < 10 and reads after the 5th item of the array.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.