C语言中的双指针和二维数组

3

我正在尝试使用双指针访问一个二维数组

int x[2][2] = {{10, 20},{30, 40}};
int *xp;
int **xpp;

printf ("%d  %d\n%d  %d\n", x[0][0], x[0][1], x[1][0], x[1][1]);
printf ("\n");

xp = *x;
printf ("%d  %d\n%d  %d\n", *xp, *(xp + 1), *(xp + 2), *(xp + 3));
printf ("\n");

xpp = (int**)x;
printf ("%d\n", **xpp);

我得到的是:

10  20
30  40

10  20
30  40

Segmentation fault

问题:我应该如何使用xpp访问数组?


为什么在 xpp = (int**)x; 中要进行 (int**) 类型转换?这个转换提示着代码在做一些“我比你编译器更了解,所以按照我的指示执行,不要报错”的事情。 - chux - Reinstate Monica
对的。如果没有强制类型转换,我会得到“warning:assignment from incompatible pointer type”警告。使用xpp访问数组的最佳方法是什么? - Jav
1
使用xpp访问数组的最佳方式-->请勿使用int **xpp; - 这不是正确的类型。 - chux - Reinstate Monica
1个回答

4

Rather than ...

int x[2][2] = {{10, 20},{30, 40}};
int **xpp;
xpp = (int**)x;

注意到表达式中的x会被转换为指向第一个元素的指针。 x 的第一个元素是x[0],类型为int [2],所以需要的类型是int (*)[2]指向 int 数组 2 的指针

int (*p)[2];
p = x;

printf ("%p\n", (void *) p);
printf ("%p\n", (void *) *p);
printf ("%d\n", **p);
printf ("%d %d %d %d\n", p[0][0], p[0][1], p[1][0], p[1][1]);

输出

0xffffcbd0 (sample)
0xffffcbd0 (sample)
10
10 20 30 40

提示:避免使用强制类型转换 - 它经常会隐藏编程中的弱点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接