[英]How can I declare an array inside a function according to the size of a parameter?
[英]How to declare/set size of global array from inside a function on Arduino?
我的 Arduino 項目中有一個 class(Arduino 基本上只是 C++)。 我有一個名為“canvas”的二維數組。 我想在 class 的開頭將數組初始化為變量。 我的 class 中有一個 function 用於將所需的 canvas 尺寸傳遞給 ZA2F2ED4F8EBC2CBBDZC21A26 我想從這個 function 內部創建這個具有正確尺寸的數組,但是數組的 scope 將不是全局的。
我該怎么做才能將數組創建為全局 class 變量,但從 function 內部設置數組的大小?
編輯澄清,這就是我想要發生的事情:
class foo{
int canvas[][];
void setupCanvas(int canvasX, int canvasY){
//I want to set the size of array "canvas" here.
//my other option is to initialise the array "canvas" here with
//dimensions canvasX and canvasY.
//Obviously that wouldn't work because I need this variable to
//be global.
}
};
希望您的問題是您不知道如何在 class 中動態創建成員 arrays。
using namespace std;
// create your class
class MyClass {
int m_canvasX; // we need store the array size somewhere
public:
int** m_canvas;
// assign a value to your member in a method
void setupCanvas(const int canvasX = 1, const int canvasY = 1){
m_canvasX = canvasX;
m_canvas = new int*[canvasX];
for(int x = 0; x < m_canvasX; x++)
m_canvas[x] = new int[canvasY];
// store a value for demonstration
m_canvas[canvasX-1][canvasY-1] = 1234;
}
~MyClass(){
for(int x = 0; x < m_canvasX; x++)
delete[] m_canvas[x];
delete[] m_canvas;
}
};
int main(){
// create an instance of your class
int sizeX = 2;
int sizeY = 3;
MyClass example;
example.setupCanvas(sizeX, sizeY);
// print the value to proof that our code actually works
cout << example.m_canvas[sizeX-1][sizeY-1];
return 0;
}
在 arduino 上,空間通常非常有限,這意味着通常要避免大規模使用動態 memory 管理,因為這會導致 memory 在較長時間內產生碎片。
以下解決方案本身不使用動態分配:
constexpr int foo_max_elements = 1024;//use #define instead if compiler doesn't support constexpr
class foo{
int canvas[foo_max_elements];
int size_x;
int size_y;
public:
void foo(int canvasX, int canvasY) : size_x{canvasX}, size_y{canvasX} {
if (size_x*size_y > foo_max_elements ) {
//too large: handle error
}
}
};
主要缺點是該解決方案總是使用相同數量的存儲空間,這意味着較小對象的浪費。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.