開發平台(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;
}