文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>数组名取地址究竟是什么?

数组名取地址究竟是什么?

时间:2010-10-15  来源:soaringdream

对于名字为a的数组,a和&a究竟有什么区别?

看一段程序:
#include <stdio.h>

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 <http://gnu.org/licenses/gpl.html>
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:
<http://www.gnu.org/software/gdb/bugs/>...
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的运算结果不一样。

相关阅读 更多 +
排行榜 更多 +
怪物餐厅正版

怪物餐厅正版

模拟经营 下载
粉碎火柴人无限金币版

粉碎火柴人无限金币版

休闲益智 下载
粉碎火柴人无敌版

粉碎火柴人无敌版

休闲益智 下载