看一段代码
int main(int argc, char **argv)
{
int b[2] = { 1, 2};
int c[2] = { 3, 4};
int *d[2] = { b, c};
int e[2][2] = {5, 6, 7, 8};
int **f = d;
int **g = e;
printf("b %p c %p\n", b, c);
printf("d[0] %p d[1] %p\n", d[0], d[1]);
printf("d[0][0] %d d[1][0] %d\n", d[0][0], d[1][0]);
printf("e[0] %p e[1] %p\n", e[0], e[1]);
printf("e[0][0] %d e[1][0] %d\n", e[0][0], e[1][0]);
printf("f[0][0] %d f[1][0] %d\n", f[0][0], f[1][0]);
printf("g[0][0] %d g[1][0] %d\n", g[0][0], g[1][0]);
}
编译报告警:
test2.c: In function ‘main’:
test2.c:14:19: warning: initialization of ‘int **’ from incompatible pointer type ‘int (*)[2]’ [-Wincompatible-pointer-types]
14 | int **g = e;
| ^
运行崩溃:
b 0x7ffc9f1550f8 c 0x7ffc9f1550f0
d[0] 0x7ffc9f1550f8 d[1] 0x7ffc9f1550f0
d[0][0] 1 d[1][0] 3
e[0] 0x7ffc9f1550d0 e[1] 0x7ffc9f1550d8
e[0][0] 5 e[1][0] 7
f[0][0] 1 f[1][0] 3
Segmentation fault (core dumped)
打印g的时候崩溃了,显然二维数组不能转换为二级指针。
二维数组一段连续的内存,实际上是一级指针:int (*)[2]
e[1][1] <=>
int (*a)[2] = e;
int *b = &a[1];
int c = b[1];
二级指针,每个元素存储的是另一个内存的地址,
f[1][1] <=>
int *b = f[1];
int c = b[1];
区别在于取b的时候,二维数组是,e偏移一段位移
而二级指针,是读取内存中的地址。