Sizeof() causes Arduino RP2040 Connect to malfunction?

On the Arduino Nano RP2040 Connect, whenever I run a sketch using the sizeof() function, the Nano starts blinking the orange light with 3 long pulses, then 3 short pulses, repeating. On Windows, the COM port is no longer recognized, and I sometimes get a notification saying something like "The USB device has malfunctioned, try plugging it in again". Oddly enough, the sketch with the sizeof() worked at some point on the Connect, but recently started throwing this weird error.

The fact that the function doesn't work is workaround-able, but the fact that every time I run a sketch with sizeof() I have to reset it in bootloader mode is troubling. Here's an example sketch below:

int test [4] = {5, 4, 3, 2};
void setup() {
  // put your setup code here, to run once:
  for (int k = 0; k < sizeof(test); k++) { //works just fine if I replace "sizeof(test)" with "4"
    pinMode(test[k], OUTPUT);
  }
}

Also, I haven't seen anything on the documentation about the orange light flashing in that pattern (3 long, 3 short pulses), so any info on that would be great too.

Sizeof is not a function but an operator which returns the number of bytes…

So sizeof(test) is likely 16 or would be 8 on a UNO… you are overstepping the boundaries of your array

To get the number of elements in an array you do

const size_t arrayCount = sizeof test / sizeof test[0];

ie you divide the total number of bytes for the array by the number of bytes used by one element of the array.

Ps as it’s an operator you can write sizeof test Without the parenthesis

1 Like

That solved it. Thanks for the help!

I guess 3 short 3 long 3 short Blinks is SOS in Morse code… your board was calling for help :wink:

2 Likes

If you have your Preferences->Compiler warnings: turned up to 'All' you would have gotten this helpful warning:

/Users/john/Documents/Arduino/sketch_may19a/sketch_may19a.ino:7:19: warning: iteration 4 invokes undefined behavior [-Waggressive-loop-optimizations]
     pinMode(test[k], OUTPUT);
             ~~~~~~^
/Users/john/Documents/Arduino/sketch_may19a/sketch_may19a.ino:5:21: note: within this loop
   for (int k = 0; k < sizeof(test); k++)   //works just fine if I replace "sizeof(test)" with "4"
                   ~~^~~~~~~~~

That's telling you that you are going beyond the limit of your array.

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