0
\$\begingroup\$

I am using the following code to create an array of pin to use in my Arduino sketch:

int LEDS[] = {7, 8, 9, 10};
int wait = 100;
int pinCount = 10;

void setup(){
  for(int PIN=7; PIN < pinCount; PIN++){
    pinMode(PIN, OUTPUT);
  }

  Serial.begin(9600);
  Serial.print("First LED: ");
  Serial.println(LEDS[0]);

  Serial.print("LED Array Size: ");
  Serial.println(sizeof(LEDS));

  for(int i=0; i < sizeof(LEDS); i++){
    Serial.print("Testing Array Index[");
    Serial.print(i);
    Serial.print("] with value: ");
    Serial.print(LEDS[i]);
    Serial.println('***********);
  }
}

It seems to me to be quite simple but I get a value twice the actual size of my array and the data in the indexes are not intelligible. Below is sample output:

First LED: 7
LED Array Size: 8
Testing Array Index[0] with value: 710794
Testing Array Index[1] with value: 810794
Testing Array Index[2] with value: 910794
Testing Array Index[3] with value: 1010794
Testing Array Index[4] with value: 10010794
Testing Array Index[5] with value: 1010794
Testing Array Index[6] with value: 010794
Testing Array Index[7] with value: 010794

Can anyone please assist and help me get the correct number of indexes and the data, please?

\$\endgroup\$
4
\$\begingroup\$

sizeof on an array gives you the size of the entire array in bytes. You need to divide this by the size of a single element in order to get the number of elements.

sizeof(LEDS) / sizeof(LEDS[0])
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.