double pointers and 2d arrays in c

不想你离开。 提交于 2020-01-30 06:07:17

问题


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\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?


回答1:


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\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.



来源:https://stackoverflow.com/questions/57068408/double-pointers-and-2d-arrays-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!