[英]double pointers and 2d arrays in c
I'm trying to access a 2D array using double pointer 我正在尝试使用双指针访问2D数组
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);
What I get is: 我得到的是:
10 20 30 40 10 20 30 40 Segmentation fault
Question: How should I access the array using xpp
? 问题:如何使用
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. ...意识到表达式中的
x
将指针转换为第一个元素的地址。 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 . 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]);
Output 产量
0xffffcbd0 (sample)
0xffffcbd0 (sample)
10
10 20 30 40
Tip: avoid casting - it often hides weak programming. 提示:避免投射 - 它经常隐藏弱编程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.