Robofun 機器人論壇

標題: 數個Array問題? [打印本頁]

作者: pizg    時間: 2012-12-7 08:52
標題: 數個Array問題?
本帖最後由 pizg 於 2012-12-7 09:46 編輯

請教各位前輩:

1. 如果陣列元素並非單一性質,

例如  a[] = { "A1028235343", "apple" , "60-3-7", 165.3};

該如何宣告?


2. 該如何知道Array的元素數量?


3. 如果已先宣告並給值, 如下

int a[]={0,1,2};

該如何動態新增一個Array元素?


4.假設

int a1[]={0,1,2};
int a2[]={0,1,2,3};

該如何a2的值複製給a1?
作者: coopermaa    時間: 2012-12-8 09:15
本帖最後由 coopermaa 於 2012-12-8 09:19 編輯

1. 如果陣列元素並非單一性質,

例如  a[] = { "A1028235343", "apple" , "60-3-7", 165.3};

該如何宣告?

C/C++ 應該是不允許 array 裏存放不同種類的 data types
建議考慮改用 struct 或是 class

2. 該如何知道Array的元素數量?

sizeof (a)  / sizeof (a[0])

3. 如果已先宣告並給值, 如下

int a[]={0,1,2};

該如何動態新增一個Array元素?

這是固定陣列,在宣告時就已決定陣列元素數量,應該不能再動態新增元素
改用指標的話應該辦得到,可以參考這篇的說明:
http://www.fredosaurus.com/notes-cpp/newdelete/50dynamalloc.html

int* a = NULL;   // Pointer to int, initialize to nothing.
int n;           // Size needed for array
cin >> n;        // Read in the size
a = new int[n];  // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
    a = 0;    // Initialize all elements to zero.
}
. . .   // Use a as a normal array
delete [] a;  // When done, free memory pointed to by a.
a = NULL;     // Clear a to prevent using invalid memory reference.

4.假設

int a1[]={0,1,2};
int a2[]={0,1,2,3};

該如何a2的值複製給a1?

我可以想得到的是只有一個笨方法,跑個迴圈複製每
元素
不過 a1 陣列 size 小於 a2,容量不夠,沒辦法完全複製過去



作者: pizg    時間: 2012-12-10 23:49
本帖最後由 pizg 於 2012-12-11 00:11 編輯

感謝cooper老師的答覆.
cin >> n;

這cin是怎麼來的?
它的作用是什麼?
作者: pizg    時間: 2012-12-10 23:57
本帖最後由 pizg 於 2012-12-11 00:31 編輯

感謝cooper老師的答覆.
我在您提供的網址內找到動態配置的程式, 如下:

  1. int max = 10; // no longer const
  2. int* a = new int[max]; // allocated on heap
  3. int n = 0;

  4. //--- Read into the array
  5. while (cin >> a[n]) {
  6. n++;
  7. if (n >= max) {
  8. max = max * 2; // double the previous size
  9. int* temp = new int[max]; // create new bigger array.
  10. for (int i=0; i<n; i++) {
  11. temp[i] = a[i]; // copy values to new array.
  12. }
  13. delete [] a; // free old array memory.
  14. a = temp; // now a points to new array.
  15. }
  16. }
  17. //--- Write out the array etc.
複製代碼

呵~~但我實在是愚笨, 還無法消化它.

我之所以會有Array的問題,
是因為我想在Arduino裏處理簡單的資料庫,
這資料庫存放著一些"定時器"的資料,
我希望隨時可以增刪這些資料, 例如:

db[0]=12;
db[1]=75;
db[2]=63;

我想再新增

db[3]=81;

請問該如何寫這動態新增?
作者: coopermaa    時間: 2012-12-11 01:01
感謝cooper老師的答覆.
cin >> n;

這cin是怎麼來的?
它的作用是什麼?
pizg 發表於 2012-12-10 23:49


sorry, 我是從國外網站直接貼過來的上面那個範例不是 arduino 的 code
BTW, cin 是 C++ 的 Standard input
作者: coopermaa    時間: 2012-12-11 01:10
感謝cooper老師的答覆.
我在您提供的網址內找到動態配置的程式, 如下:

呵~~但我實在是愚笨, 還無法消化 ...
pizg 發表於 2012-12-10 23:57


可能要用 malloc() 和 realloc():

http://diyroboticslab.wordpress.com/category/tutorials/arduino-tutorials/




歡迎光臨 Robofun 機器人論壇 (https://robofun.net/forum/) Powered by Discuz! X3.2