I have a few leds and i want to control them with a function, but the array doesn’t seems to arrive at the function.
Here’s my code
void setup() {
for (int i = 2; i < 8; i++) {
pinMode(i, OUTPUT);//setting pins to OUTPUT
}
int leds[] = {1,4,5,7};//make array
arrayLeds(leds);//turn all leds on in the array
}
void loop() {}//no loop today
int arrayLeds(int array[]) {
int size = sizeof(array) / sizeof(int);//get lenght of the array
for (int i = 0; i < size; i++) {
digitalWrite(array[i],HIGH); //loop through array to turn led on
}
}
int arrayLeds(int array[]) {
int size = sizeof(array) / sizeof(int);//get lenght of the array
for (int i = 0; i < size; i++) {
digitalWrite(array[i],HIGH); //loop through array to turn led on
}
}
The function doesn’t get the whole array by value. The function gets a pointer to the array. So inside this function, sizeof returns 2 which is the size of a pointer.
This is a common pitfall. There’s no way around it. If the array argument isn’t going to be a fixed size every time, then you’ll have to pass the size along as another argument.
int arrayLeds(int array[], int size) {
for (int i = 0; i < size; i++) {
digitalWrite(array[i],HIGH); //loop through array to turn led on
}
}
Delta_G:
The function doesn't get the whole array by value. The function gets a pointer to the array. So inside this function, sizeof returns 2 which is the size of a pointer.
I missed that. I would have thought that sizeof(x) where x is an array type of unknown size should have generated a compilation error. sizeof() should be using the lvalue, not the rvalue.
PaulMurrayCbr:
I missed that. I would have thought that sizeof(x) where x is an array type of unknown size should have generated a compilation error. sizeof() should be using the lvalue, not the rvalue.
In this case, x is a pointer to int, not an array of unknown size. sizeof (int *) == sizeof x, and on Arduino that is 2.
PaulMurrayCbr:
I missed that. I would have thought that sizeof(x) where x is an array type of unknown size should have generated a compilation error. sizeof() should be using the lvalue, not the rvalue.
If you look at the generated code, you will see that what it does is perfectly logical. The argument the function actually receives is a pointer, NOT an array. So, sizeof returns the size of the argument, which is the size of a pointer. This is by design, and how c has always been defined c since it was first introduced in the '70s. Were it not so, a huge amount of time, and RAM, would be wasted copying whole arrays to the stack on function calls.