简体   繁体   English

尝试将二维数组传递给 function 并出现编译器错误

[英]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.我是 C/C++ 初学者,正在尝试构建一个简单的脚本。 I'm running this on an Arduino.我在 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*)' src/main.cpp: 在 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: 在 function 'void loop()': src/main.cpp:46:37: error: cannot convert 'int ( )[3]' to 'int ' for argument '1 ' 到 'void convert_drawing_to_LEDS(int*)'
convert_drawing_to_LEDS(my_drawing); convert_drawing_to_LEDS(my_drawing); ^ Compiling.pio/build/uno/FrameworkArduino/WInterrupts.c.o *** [.pio/build/uno/src/main.cpp.o] Error ^ Compiling.pio/build/uno/FrameworkArduino/WInterrupts.c.o *** [.pio/build/uno/src/main.cpp.o] 错误

Can anyone help me?谁能帮我?

Thanks!谢谢!

You've declared convert_drawing_to_LEDS to take an int [] which is not a 2D array.您已声明convert_drawing_to_LEDS以采用非二维数组的int [] 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.这会导致参数与其在 function 中的使用方式不匹配,以及传入的实际参数与 function 所期望的不匹配。

You instead want:你反而想要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM