对于名字为a的数组,a和&a究竟有什么区别?
看一段程序:
#include
int main(int argc, char** argv){
int a[5] = {1,2,3,4,5};
int (*ptr)[5] = &a+1;
printf("%d\n",*(a+1));
printf("%d\n",(*(ptr-1))[2]);
return 0;
}
运行结果:
2
3
再看看gdb的结果:
[hux@nextproxy02 test_src]$ gdb test
GNU gdb (GDB) 7.2
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu".
For bug reporting instructions, please see:
<
Reading symbols from /home/hux/test_src/test...done.
(gdb) b main
Breakpoint 1 at 0x8048386: file test.c, line 4.
(gdb) r
Starting program: /home/hux/test_src/test
Breakpoint 1, main (argc=1, argv=0xbffffa64) at test.c:4
4 int a[5] = {1,2,3,4,5};
(gdb) n
5 int (*ptr)[5] = &a+1;
(gdb) p &a
$1 = (int (*)[5]) 0xbffff9b0
(gdb) p &a[0]
$2 = (int *) 0xbffff9b0
(gdb) p &a + 1
$3 = (int (*)[5]) 0xbffff9c4
(gdb) p &a[0] + 1
$4 = (int *) 0xbffff9b4
(gdb)
也就是说:
a可以看作是pointer to int,等于&a[0]。
&a可以看作是pointer to array of 5 ints。
所以&a+1,这里的“1”是指5*sizeof(int)。
指针运算结果按自身类型计算,所以它们+1的运算结果不一样。
阅读(710) | 评论(0) | 转发(0) |