[問題]scanf讀進variable length array問題

作者: codefarmer (自信)   2017-09-14 00:02:50
開發平台(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;
}
作者: ilikekotomi (Young)   2017-09-14 00:13:00
num的值是在定義之後給的 這樣s和t的陣列大小不是5
作者: jerryh001   2017-09-14 00:13:00
宣告陣列的時候 num還是未知數
作者: windada2 (如此重要)   2017-09-15 01:17:00
陣列設置初始大小是不能用變數的呦
作者: LPH66 (-6.2598534e+18f)   2017-09-15 01:33:00
C99 可以, gcc 在 C90 模式和 C++ 是以 extension 支援

Links booklink

Contact Us: admin [ a t ] ucptt.com