Robofun 機器人論壇

 找回密碼
 申請會員
搜索
熱搜: 活動 交友 discuz
查看: 7024|回復: 5
打印 上一主題 下一主題

數個Array問題?

[複製鏈接]
跳轉到指定樓層
1#
發表於 2012-12-7 08:52:48 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
本帖最後由 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?
2#
發表於 2012-12-8 09:15:44 | 只看該作者
本帖最後由 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,容量不夠,沒辦法完全複製過去


3#
 樓主| 發表於 2012-12-10 23:49:41 | 只看該作者
本帖最後由 pizg 於 2012-12-11 00:11 編輯

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

這cin是怎麼來的?
它的作用是什麼?
4#
 樓主| 發表於 2012-12-10 23:57:04 | 只看該作者
本帖最後由 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;

請問該如何寫這動態新增?
5#
發表於 2012-12-11 01:01:38 | 只看該作者
感謝cooper老師的答覆.
cin >> n;

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


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

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


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

http://diyroboticslab.wordpress.com/category/tutorials/arduino-tutorials/
您需要登錄後才可以回帖 登錄 | 申請會員

本版積分規則

小黑屋|手機版|Archiver|機器人論壇 from 2005.07

GMT+8, 2024-6-29 14:26 , Processed in 0.475051 second(s), 7 queries , Apc On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表