本文介绍了c中的双指针和二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用双指针访问二维数组
int x[2][2] = {{10, 20},{30, 40}};国际*xp;国际**xpp;printf ("%d %d
%d %d
", x[0][0], x[0][1], x[1][0], x[1][1]);printf ("
");xp = *x;printf ("%d %d
%d %d
", *xp, *(xp + 1), *(xp + 2), *(xp + 3));printf ("
");xpp = (int**)x;printf ("%d
", **xpp);
我得到的是:
10 2030 4010 2030 40分段故障
问题:我应该如何使用 xpp
访问数组?
解决方案
而不是 ...
int x[2][2] = {{10, 20},{30, 40}};国际**xpp;xpp = (int**)x;
... 意识到表达式中的 x
将第一个元素的地址转换为指针.x
的第一个元素是x[0]
,它的类型是int [2]
,所以需要的类型是int(*)[2]
或 指向int 数组 2.
int (*p)[2];p = x;printf ("%p
", (void *) p);printf ("%p
", (void *) *p);printf ("%d
", **p);printf ("%d %d %d %d
", p[0][0], p[0][1], p[1][0], p[1][1]);
输出
0xffffcbd0(示例)0xffffcbd0(样本)1010 20 30 40
提示:避免强制转换 - 它通常隐藏弱编程.
I'm trying to access a 2D array using double pointer
int x[2][2] = {{10, 20},{30, 40}};
int *xp;
int **xpp;
printf ("%d %d
%d %d
", x[0][0], x[0][1], x[1][0], x[1][1]);
printf ("
");
xp = *x;
printf ("%d %d
%d %d
", *xp, *(xp + 1), *(xp + 2), *(xp + 3));
printf ("
");
xpp = (int**)x;
printf ("%d
", **xpp);
What I get is:
Question: How should I access the array using xpp
?
解决方案
Rather than ...
int x[2][2] = {{10, 20},{30, 40}};
int **xpp;
xpp = (int**)x;
... realize that x
in the expression converts to a pointer the address of the first element. The first element of x
is x[0]
which has a type of int [2]
, so the type needed is int (*)[2]
or pointer to array 2 of int.
int (*p)[2];
p = x;
printf ("%p
", (void *) p);
printf ("%p
", (void *) *p);
printf ("%d
", **p);
printf ("%d %d %d %d
", p[0][0], p[0][1], p[1][0], p[1][1]);
Output
0xffffcbd0 (sample)
0xffffcbd0 (sample)
10
10 20 30 40
Tip: avoid casting - it often hides weak programming.
这篇关于c中的双指针和二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!