看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): Win7 編譯器: GCC 問題(Question): 程式利用scanf()讀檔案至int s[num], int t[num], 問題發生在寫入 t[4] 時, s[0]的值跟著被覆蓋, 利用printf印出 t[4] 跟 s[0]的 address 發現兩者相同... 想請問大神們, 明明是兩個不同的ARRAY, 為何compiler 將兩者的element 放在相同位址? 是否是小弟有疏忽,才造成這樣的情形呢? 餵入的資料(Input): 5 1 2 4 6 8 3 5 7 9 10 預期的正確結果(Expected Output): num = 5 t[i] = 3; s[0] = 1 t[i] = 5; s[0] = 1 t[i] = 7; s[0] = 1 t[i] = 9; s[0] = 1 t[i] = 10; s[0] = 1 錯誤結果(Wrong Output): num = 5 t[i] = 3; s[0] = 1 t[i] = 5; s[0] = 1 t[i] = 7; s[0] = 1 t[i] = 9; s[0] = 1 t[i] = 10; s[0] = 10 &s[0] = 0xffffcb80, &t[4] = 0xffffcb80 程式碼(Code): #include <stdio.h> int main(int argc, char const *argv[]) { const int num; int s[num]; int t[num]; scanf("%d", &num); printf("num = %d\n", num); for (int i = 0; i < num; ++i) scanf("%d", &s[i]); for (int i = 0; i < num; ++i) { scanf("%d", &t[i]); printf("t[i] = %d; s[0] = %d\n", t[i], s[0]); } printf("&s[0] = %p, &t[4] = %p\n", &s[0], &t[4]); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.224.46.108 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1505318573.A.3A7.html
ilikekotomi: num的值是在定義之後給的 這樣s和t的陣列大小不是5 09/14 00:13
jerryh001: 宣告陣列的時候 num還是未知數 09/14 00:13
windada2: 陣列設置初始大小是不能用變數的呦 09/15 01:17
LPH66: C99 可以, gcc 在 C90 模式和 C++ 是以 extension 支援 09/15 01:33