Home > Back-end >  Trying to pass 2D array to function and getting a compiler error
Trying to pass 2D array to function and getting a compiler error

Time:03-08

I'm a C/C beginner and trying to build a simple script. I'm running this on an Arduino.

#include <Arduino.h>

int pin_locations[3][3] = {
  {8,  5, 4},
  {9,  6, 3},
  {10, 7, 2}
};

void setup() {
  for (int i=0; i<3;   i) {
    for (int j=0; j<3;   j) {
      pinMode(pin_locations[i][j], OUTPUT);
    }
  }
}

void convert_drawing_to_LEDS(int drawing[]) {
  for (int i=0; i<3;   i) {
    for (int j=0; j<3;   j) {
      if (drawing[i][j] == 1) {
        digitalWrite(pin_locations[i][j], HIGH);
      }
    }
  }
}

void loop() {
  // drawing
  int my_drawing[3][3] = {
    {1, 1, 1},
    {1, 0, 1},
    {1, 1, 1}
  };

  convert_drawing_to_LEDS(my_drawing);

}

But it gives me two errors:

src/main.cpp: In function 'void convert_drawing_to_LEDS(int*)': src/main.cpp:31:23: error: invalid types 'int[int]' for array subscript if (drawing[i][j] == 1) { ^ src/main.cpp: In function 'void loop()': src/main.cpp:46:37: error: cannot convert 'int ()[3]' to 'int' for argument '1' to 'void convert_drawing_to_LEDS(int*)'
convert_drawing_to_LEDS(my_drawing); ^ Compiling .pio/build/uno/FrameworkArduino/WInterrupts.c.o *** [.pio/build/uno/src/main.cpp.o] Error

Can anyone help me?

Thanks!

CodePudding user response:

You've declared convert_drawing_to_LEDS to take an int [] which is not a 2D array. This causes a mismatch between the parameter and how its being used in the function, and also a mismatch between the actual parameter being passed in and what the function is expecting.

You instead want:

void convert_drawing_to_LEDS(int drawing[3][3]) {
  • Related