剛剛被檢查在gdb以下幾點:C類優化
char *a[] = {"one","two","three","four"};
char *b[] = {"one","two","three","four"};
char *c[] = {"two","three","four","five"};
char *d[] = {"one","three","four","six"};
,我得到以下幾點:
(gdb) p a
$17 = {0x80961a4 "one", 0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four"}
(gdb) p b
$18 = {0x80961a4 "one", 0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four"}
(gdb) p c
$19 = {0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four", 0x80961b7 "five"}
(gdb) p d
$20 = {0x80961a4 "one", 0x80961ac "three", 0x80961b2 "four", 0x80961bc "six"}
我真的很驚訝,字符串指針等效相同話。我原以爲每個字符串都會被分配到自己的內存中,而不管它是否與另一個數組中的字符串相同。
這是某種編譯器優化的例子,還是這種類型的字符串聲明的標準行爲?
「堆棧」在這個問題中甚至來自哪裏?如果你將'a','b','c'和'd'聲明爲局部變量,你必須在你的問題中這麼說。 – AnT 2012-07-09 17:07:15
是 - 它們是在函數中聲明的自動持續時間的局部變量,因此在堆棧中 – bph 2012-07-09 17:10:52
是的。這是編譯器優化的一個例子。 – Jack 2012-07-09 17:27:04