Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to pass 2D array to function and getting a compiler error

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can anyone help me?

Thanks!

>Solution :

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]) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading