通過3個程序分析數組與指針區別

通過3個程序分析數組與指針區別

總結:

1.指針本身需要佔用內存空間,指針的值是指向位置的地址(例如c

2.數組名實際就是個地址。數組名的值是個指針常量,也就是數組第一個元素的地址,所以,數組名這個指針並不需要像普通指針c那樣佔用內存空間,它實際就是一個地址0xbffff3c8,在這個地址裏存儲的就是數組第一個元素。b=&b

 

程序1:

  

 

Output:

&a is 0xbffff3cc

a is 12

&b is 0xbffff3c8

b is 0xbffff3c8

*b is 12

&c is 0xbffff3c4

c is 0xbffff3c8

 

Breakpoint 1, main () at free_test.c:15

15      return 0;

(gdb) x /4xb 0xbffff3cc

0xbffff3cc: 0x0c    0x00    0x00    0x00

(gdb) x /4xb 0xbffff3c8

0xbffff3c8: 0x0c    0x00    0x00    0x00

(gdb) x /4xb 0xbffff3c4

0xbffff3c4: 0xc8    0xf3    0xff    0xbf

 

分析:

 

注意:

1.指針的值是指向位置的地址(例如c

2.數組名的值是個指針常量,也就是數組第一個元素的地址,所以,數組名這個指針並不需要像普通指針c那樣佔用內存空間,它實際就是一個地址0xbffff3c8,在這個地址裏存儲的就是數組第一個元素。b=&b

 

程序2

 

 

  

 

Output:

&a is 0xbffff3cc

a is 12

&b is 0xbffff3c8

b is 0xbffff3cc

*b is 12

&c is 0xbffff3c4

c is 0xbffff3c8

 

Breakpoint 1, main () at free_test.c:34

34      return 0;

(gdb) x /4xb 0xbffff3c4

0xbffff3c4: 0xc8    0xf3    0xff    0xbf

(gdb) x /8xb 0xbffff3c4

0xbffff3c4: 0xc8    0xf3    0xff    0xbf    0xcc    0xf3    0xff    0xbf

(gdb) x /12xb 0xbffff3c4

0xbffff3c4: 0xc8    0xf3    0xff    0xbf    0xcc    0xf3    0xff    0xbf

0xbffff3cc: 0x0c    0x00    0x00    0x00

 

分析:

 

與程序2對比,可知當把b定義爲指針時,b!=&b

 

看懂以上兩個程序,第三個也就不難理解了。

程序3:

  

Output:

root@fc-desktop:~/Documents/sourcefile/free_test# ./free_test &strings is 0xbfee2d64

strings is  0xbfee2d64

*strings is 0x8048620

 

&strings[0] is   0xbfee2d64

strings[0] is    0x8048620

*strings[0] is   h

strings[0][0] is h

 

&strings[1] is   0xbfee2d68

strings[1] is    0x8048626

*strings[1] is   w

strings[1][0] is w

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章