我计划编写一个修改二维数组的函数,以便每个坐标都设置为0.在setup()
我声明了displayWidth
和displayHeight
但是可以'在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(){}
答案 0 :(得分:4)
全局声明board
,displayWidth
和displayHeight
(在任何函数定义之外)。像这样:
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()中声明它们使它们成为局部变量 - 局部变量只能被声明它们的函数访问。