作者ric2k1 (Ric)
看板EE_DSnP
標題[討論] Array size 的問題
時間Wed Dec 5 22:21:32 2007
有同學寫了這樣的程式:
int x;
cin >> x;
int a[x];
// ... 使用 a[x]...
結果沒有問題且執行正確.
理論上 int a[x] 的 size 要是 constant 然後 compiler 才能在 compile time 決定
sizeof(a). (還記得 sizeof 是 compile time operator).
那這裡是怎麼回事呢?
我做了一個實驗:
==============================================
int main()
{
int x;
cin >> x;
int a[x];
cout << "sizeof(a) = " << sizeof(a) << endl;
cout << "&a = " << &a << endl;
cout << " a = " << a << endl;
cout << "&a[0] = " << &a[0] << endl;
cout << "&a[1] = " << &a[1] << endl;
cout << "&a[9] = " << &a[9] << endl;
int b[10];
cout << "sizeof(b) = " << sizeof(b) << endl;
cout << "&b = " << &b << endl;
cout << " b = " << b << endl;
cout << "&b[0] = " << &b[0] << endl;
cout << "&b[1] = " << &b[1] << endl;
cout << "&b[9] = " << &b[9] << endl;
int c[10];
cout << "&c = " << &c << endl;
cout << " c = " << c << endl;
cout << "&c[0] = " << &c[0] << endl;
cout << "&c[1] = " << &c[1] << endl;
cout << "&c[9] = " << &c[9] << endl;
}
=============================================
結果輸出是 (on Linux):
10
sizeof(a) = 40
&a = 0xfef7e770
a = 0xfef7e770
&a[0] = 0xfef7e770
&a[1] = 0xfef7e774
&a[9] = 0xfef7e794
sizeof(b) = 40
&b = 0xfef7e7f0
b = 0xfef7e7f0
&b[0] = 0xfef7e7f0
&b[1] = 0xfef7e7f4
&b[9] = 0xfef7e814
&c = 0xfef7e7c0
c = 0xfef7e7c0
&c[0] = 0xfef7e7c0
&c[1] = 0xfef7e7c4
&c[9] = 0xfef7e7e4
We can see:
1. sizeof(a) = 40!! 所以顯然 sizeof(a) 並不是 compile time 就決定的, 因為
x 是 cin 才指定為 10 的.
查了許多網頁都是一面倒的說 sizeof is a compile time operator...
只有一個 IBM Mac OS X/XL C++ compiler 說:
"At compile time, the compiler analyzes the expression to determine its
type, but does not evaluate it...."
Anyway, it's a mystery...
2. a 的 memory address 比 b and c 小!!
Since stack memory gives away its memory in the reverse addressing order,
that means 程式先給了 b[10] and c[10] 的 memory space 才給 a[10].
也就是說, 程式進入 main() 之後就先將 local varible b[10], c[10] 的 memory
準備好, 然後執行到 a[x] 才去決定要用多少 memory 來存 a.
===================================
喔, 對了, 對 int a[x] 如果 x is not a constant 是不能用 initializer list 來
initialize a[x] 的值 (e.g. int a[x] = { 0 } ).
因為 sizeof({0}) 還是有可能比 sizeof(a[x]) 還要大...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.121.132.121
※ 編輯: ric2k1 來自: 59.121.132.121 (12/05 22:28)
1F:推 ilway25:選課程式有用到這樣,G++過,VC不給過.. 12/05 22:44
2F:推 ric2k1:不過忘了說, 這樣寫是不好的... 12/05 23:03
3F:推 ilway25:所以還是用pointer new比較好? 話說strtok後要不要delete? 12/05 23:06
4F:推 timrau:This is a GCC extension. 12/05 23:28
6F:推 ric2k1:Cool, so it is safe if the compiler supports it. 12/05 23:41
7F:推 ric2k1:strtok 不用 "額外" 去 delete. 12/05 23:42
8F:推 lionel20002:原來如此 話說我常這樣寫... 12/06 00:37