我刚刚在 gdb 中检查了以下内容:
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"}
我真的很惊讶字符串指针对于等效单词是相同的。我原以为每个字符串都会在堆栈上分配自己的内存,而不管它是否与另一个数组中的字符串相同。
这是某种编译器优化的例子,还是这种字符串声明的标准行为?