Arduino - 在setup()中声明的变量不在函数范围内

时间:2015-02-12 20:50:01

标签: c++ arduino

我计划编写一个修改二维数组的函数,以便每个坐标都设置为0.在setup()我声明了displayWidthdisplayHeight但是可以'在generateBoard()函数中访问它们,因为它们不在同一范围内。

代码:

void generateBoard(int board[][]) {
  // Modifies the array board by setting zeros

  for (int y=0; y < displayHeight; y++) {
    for (int x=0; x < displayWidth; x++) {
      board[x][y] = 0;
    }
  }
}

void setup() {
  int displayWidth  = 14;
  int displayHeight = 10;

  int board[displayWidth][displayHeight];
  generateBoard(board); 
}

void loop() {}

设置()

中的本地范围异常
error: declaration of 'board' as multidimensional array must have bounds for all dimensions except the first
error: declaration of 'board' as multidimensional array must have bounds for all dimensions except the first
In function 'void generateBoard(...)':
error: 'displayHheight' was not declared in this scope
error: 'displayWidth' was not declared in this scope
error: 'board' was not declared in this scope

固定版和工作版:

const int displayWidth  = 14;
const int displayHeight = 10;
int board[displayWidth][displayHeight];

void generateBoard() {
  // Modifies the array board by setting zeros

  for (int y=0; y < displayHeight; y++) {
    for (int x=0; x < displayWidth; x++) {
      board[x][y] = 0;
    }
  }
}

void setup() {
  generateBoard(); 
}

void loop(){}

1 个答案:

答案 0 :(得分:4)

全局声明boarddisplayWidthdisplayHeight(在任何函数定义之外)。像这样:

 const int displayWidth  = 14;
 const int displayHeight = 10;
 int board[displayWidth][displayHeight];

void generateBoard() {
  // Modifies the array board by setting 0

  for (int y=0; y < displayHeight; y++) {
    for (int x=0; x < displayWidth; x++) {
      board[x][y] = 0;
    }
  }
}

void setup() {
  generateBoard(); 
}

void loop() {}

在setup()中声明它们使它们成为局部变量 - 局部变量只能被声明它们的函数访问。