传递指针时的错误,以结构的数组 [英] Error when passing pointer to array of structs
本文介绍了传递指针时的错误,以结构的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdio.h>
#include <stdlib.h>
struct Point {
double x;
};
void test(struct Point **a, int len)
{
int i;
printf("a = %p\n", a);
for (i = 0; i < len; ++i)
printf("%f\n", a[i]->x);
}
int main()
{
int i;
int len = 4;
struct Point *P;
P = malloc(len*sizeof(struct Point));
for (i = 0; i < len; ++i) {
P[i].x = i;
printf("%f\n", P[i].x);
}
printf("&P = %p\n", &P);
test(&P, len);
return 0;
}
我试图结构的数组传递给一个函数(我想一个指针传递到阵列中,不能复印)。当我尝试使用函数内部数组中,我得到一个访问冲突。什么是做到这一点的正确方法?我究竟做错了什么? A ==&安培; P
,所以它应该工作,对
推荐答案
为什么是你想有一个结构点**
?您可以在同一改写为
Why's you want a struct Point **
? You can rewrite the same as
void test(struct Point *a, int len)
{
//some stuff
printf("%f\n", a[i].x);
}
和调用它像
test(P, len);
这样的话,恕我直言,要求
This way, IMHO, the requirement
的我想一个指针传递给数组的
时,也遇到了#。
(#)注:要严格,我们在这里通过的指向数组的第一个元素的,但是,行为比较平等的。感谢先生的 @alk 作为评论。
(#) NOTE: To be strict, here we pass the pointer to the first element of the array, however, the behaviour compares equal. Thanks to Mr. @alk for the comment.
这篇关于传递指针时的错误,以结构的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文