C数组内存分布

数组内存中分布情况

  1. 二维数组
    注意栈中地址是从高地址向低地址生长:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
(gdb) p/x &arr[0][0]
$7 = 0x7fffffffe440
(gdb) p/x &arr[0][1]
$8 = 0x7fffffffe444
(gdb) p/x &arr[0][2]
$9 = 0x7fffffffe448
(gdb) p/x &arr[0][3]
$10 = 0x7fffffffe44c

(gdb) p/x &arr[1][0]
$11 = 0x7fffffffe450
(gdb) p/x &arr[1][1]
$12 = 0x7fffffffe454
(gdb) p/x &arr[1][2]
$13 = 0x7fffffffe458
(gdb) p/x &arr[1][3]
$14 = 0x7fffffffe45c

(gdb) p/x &arr[2][0]
$15 = 0x7fffffffe460
(gdb) p/x &arr[2][1]
$16 = 0x7fffffffe464
(gdb) p/x &arr[2][2]
$17 = 0x7fffffffe468
(gdb) p/x &arr[2][3]
$18 = 0x7fffffffe46c

(gdb) p/x &arr[3][0]
$19 = 0x7fffffffe470
(gdb) p/x &arr[3][1]
$20 = 0x7fffffffe474
(gdb) p/x &arr[3][2]
$21 = 0x7fffffffe478
(gdb) p/x &arr[3][3]
$22 = 0x7fffffffe47c

即如下图走向:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
         0     1     2    3  
0 ------------------->
1 ------------------->
2 ------------------->
3 ------------------->
```
0. 一维数组在内存中的分布情况:
```c
(gdb) p/x &a[0]
$1 = 0x7fffffffe460
(gdb) p/x &a[1]
$2 = 0x7fffffffe464
(gdb) p/x &a[2]
$3 = 0x7fffffffe468
(gdb) p/x &a[3]
$4 = 0x7fffffffe46c
(gdb) p/x &a[4]
$5 = 0x7fffffffe470
(gdb) p/x &a[5]
$6 = 0x7fffffffe474

1
2
3
低地址            高地址
a 0 1 2 3 4
--------------------->
  1. c中栈是由高地址向低地址延伸,堆则是从低地址想高地址延伸

    1
    2
    3
    4
    5
    6
    7
    8
    9
      栈底
    ___________
    | a[5] | 高地址
    | a[4] |
    | a[3] |
    | a[2] |
    | a[1] |
    | a[0] | 低地址
    栈顶
  2. C程序内存中的组织形式

【代码区    】  高地址
【静态数据区 】
【栈        】
 -----------
 -----------
 -----------
 -----------
【 堆       】 低地址
坚持原创技术分享,您的支持奖鼓励我继续创作!