通过指针的二维数组
我想借助指针扫描二维数组并编写了这段代码,你能告诉我为什么编译器会出错吗?我知道如何使用双指针来做同样的事情,我正在尝试这个。
#include<stdio.h>
#include<stdlib.h>
int main(void) {
int i,j,n,a,b;
int (*(*p)[])[];
printf("\n\tEnter the size of the matrix in the form aXb\t\n");
scanf("%dX%d",&a,&b);
p=(int (*(*p)[b])[a])malloc(b*sizeof(int (*p)[a]));
for(i=0;i<b;i++) {
p[i]=(int (*p)[a])malloc(a*sizeof(int));
printf("\t\bEnter Column %d\t\n");
for(j=0;j<a;j++)
scanf("%d",&p[i][j]);
}
return 0;
}
I want to scan a 2D array with the help of pointers and have written this code, could you tell me why the compiler gives errors? I know how to use double pointers to do the same, i was experimenting with this one.
#include<stdio.h>
#include<stdlib.h>
int main(void) {
int i,j,n,a,b;
int (*(*p)[])[];
printf("\n\tEnter the size of the matrix in the form aXb\t\n");
scanf("%dX%d",&a,&b);
p=(int (*(*p)[b])[a])malloc(b*sizeof(int (*p)[a]));
for(i=0;i<b;i++) {
p[i]=(int (*p)[a])malloc(a*sizeof(int));
printf("\t\bEnter Column %d\t\n");
for(j=0;j<a;j++)
scanf("%d",&p[i][j]);
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在使用指向数组的指针,因此您不应该直接对它们进行索引,因为
p[i]
将给出*(p+i)
即指向的数组后面的数组到 p,而不是 p 的元素。在 C 中,
void*
将转换为任何指针类型,因此您不需要转换 malloc 的结果。如果您确实放入了强制转换,它可能会掩盖错误,例如,如果您尝试分配给非指针(例如p[i]
)。在 p 的 malloc 中,sizeof(int (*p)[a]) 应该使用类型或表达式,而不是声明。
p
是一个指向 int 数组的指针数组的指针,因此*p
元素的类型为int (*)[]
。因此,在 gcc 上编译时不会出现错误或警告:
但是,由于使用指向数组的指针与使用指向其第一个元素的指针相比没有任何优势,但这确实意味着您必须在获取元素之前取消引用,因此更容易使用指针形式的指针。
You are using pointers to arrays, so you shouldn't index them directly, as
p[i]
will give*(p+i)
i.e. an array following the one pointed to by p, rather than an element of p.In C,
void*
will convert to any pointer type, so you don't need to cast the result of malloc. If you do put the casts in, it can mask errors, for example if you are trying to assign to a non-pointer ( such asp[i]
).In the malloc for p,
sizeof(int (*p)[a])
should either use a type or an expression, not a declaration.p
is a pointer to an array of pointers to arrays of int, so the type of the elements of*p
isint (*)[]
.So this compiles without error or warning on gcc:
However, since there is no advantage in using a pointer to an array against using a pointer to its first element but it does mean you have to dereference before taking the element, it is much easier to use the pointer to a pointer form.
你知道
int (*(*p)[])[]
是什么吗?尝试 cdecl.org ... http://cdecl.ridiculousfish.com/?q=int+%28%2A%28%2Ap%29%5B%5D%29%5B%5D
使用一维数组并假装它是一个二维对象
就是这样
Do you know what
int (*(*p)[])[]
is?Try cdecl.org ... http://cdecl.ridiculousfish.com/?q=int+%28%2A%28%2Ap%29%5B%5D%29%5B%5D
To use a 1-dimensional array and pretend it's a 2-dimensional one
That's it
您不必要地使使用指针访问数组元素的问题变得复杂化。
尝试使用简单的指针到指针 p。
You are unnecessarily complicating the problem of accessing array elements using pointers.
Try to use a simple pointer-to-pointer p.