[問題] 結構中有陣列時複製的問題

作者: icetofux   2019-03-25 22:00:38
開發平台(Platform): (Ex: Win10, Linux, ...)
None.
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
None.
問題(Question):
當結構中有陣列,如:
typedef struct {
uint8_t data[4];
} DATA_AREA;
typedef struct {
DATA_AREA row1;
DATA_AREA row2;
} FRAME;
如果將一個Frame變數賦值給另外一個Frame變數,如:
FRAME a, b;
...
b=a;
陣列內的值會被複製嗎?
餵入的資料(Input):
如下完整程式碼
預期的正確結果(Expected Output):
None
錯誤結果(Wrong Output):
None
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
typedef struct {
uint8_t data[4];
} DATA_AREA;
typedef struct {
DATA_AREA row1;
DATA_AREA row2;
} FRAME;
int main(int argc, char* args[]) {
FRAME a, b;
strcpy(a.row1.data, "abc");
strcpy(a.row2.data, "XYZ");
b = a;
printf("a:%s,%s\n", a.row1.data, a.row2.data);
printf("b:%s,%s\n", b.row1.data, b.row2.data);
strcpy(a.row1.data, "xyz");
strcpy(a.row2.data, "ABC");
printf("a:%s,%s\n", a.row1.data, a.row2.data);
printf("b:%s,%s\n", b.row1.data, b.row2.data);
printf("%0X ... %0X\n", &a.row1.data, &a.row2.data);
printf("%0X ... %0X\n", &b.row1.data, &b.row2.data);
}
補充說明(Supplement):
上面的code其實已經實驗完了,陣列中的資料確實會被複製過去,我一直把
陣列想像成只是一個不記憶長度的空間起始位置(就像指標那樣),這樣看起
來實際陣列知道自己的長度,可是這個長度是存在哪裡呢?
順帶一提如果把陣列換成uint8_t*然後在main裡用malloc分配空間並執行相
同實驗,實際上a跟b的rowX.data會是同樣的位置,表示它複製的是指標內
容。
作者: hsnuer1171 (阿賭)   2019-03-25 22:24:00
Array的長度是compiler記的b = a 基本上會被compiler當成memcpy(&b, &a, sizeof(a))來處理

Links booklink

Contact Us: admin [ a t ] ucptt.com