关于c语言中的结构体数组作为函数参数传递的

#include <stdio.h>
#include <math.h>
typedef struct {int x; int y;} Point;
int PointDist(Point);
int main()
{
Point d[2];
printf("Enter the x value of point1:");
scanf("%d",&d[0].x);
printf("Enter the y value of point1:");
scanf("%d",&d[0].y);
printf("Enter the x value of point2:");
scanf("%d",&d[1].x);
printf("Enter the y value of point2:");
scanf("%d",&d[1].y);
printf("The Euclidean distance between two Points is %lf",PointDist(d[2]));

system("pause");
return 0;
}
int PointDist(Point dot[2])
{
int a,b;

a=(dot[0].x-dot[1].x)+(dot[0].y-dot[1].y);
b=a+1;
return b;
}
运行时发生错误,咋回事啊

1、结构体数组传给指针,实质上是不可能的,本质上传的是数组首地址,根据偏移来操作数组,这样看起来好像是真在操作数组一样。就和普通指针一样使用,只不过它是结构体数组。
2、例程:

typedef struct Student
{
    char name[10] ;
    int age ;
}Student;
#define LEN 10 
//print all Student infomation
void fun(Student *pStu,int len)
{
    int i ; 
    for(i = 0 ;i < len ;++i)
    {
        printf("%s\t%d",pStu[i].name,pStu[i].age) ;
    }
}
int main ()
{
    Student stu[LEN] ;
    fun(stu,LEN) ;
    
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-12
printf("The Euclidean distance between two Points is %lf",PointDist(d[2]));

这一行有问题,你直接把d[2]作为参数传递过去了,d[2]是一个Point类型,而函数的形参是指针类型,所以会报错。要做的就是改成printf("The Euclidean distance between two Points is %lf",PointDist(d));就好。追问

没有报错,而是运行后出现什么冲突(我是小白),不过照您说的改后就报错了,所以还需要怎样改呢,谢谢你热情的回答

追答

int PointDist(Point);这句改成int PointDist(Point dot[])

int PointDist(Point dot[2])这句改成int PointDist(Point dot[])

整个改成这样:
#include
#include
typedef struct {int x; int y;} Point;
int PointDist(Point dot[]);
int main()
{
Point d[2];
printf("Enter the x value of point1:");
scanf("%d",&d[0].x);
printf("Enter the y value of point1:");
scanf("%d",&d[0].y);
printf("Enter the x value of point2:");
scanf("%d",&d[1].x);
printf("Enter the y value of point2:");
scanf("%d",&d[1].y);
printf("The Euclidean distance between two Points is %lf",PointDist(d));

system("pause");
return 0;
}
int PointDist(Point dot[])
{
int a,b;

a=(dot[0].x-dot[1].x)+(dot[0].y-dot[1].y);
b=a+1;
return b;
}

第2个回答  2013-12-12
printf("The Euclidean distance between two Points is %lf",PointDist(d[2]));

输出格式是%lf, 而PointDist(Point)的返回值是int型的。

还有PointDist()是求两点见的距离吗?似乎公式不对呀?

坐标最好使用float型数据,
第3个回答  2013-12-21
楼主朋友,你的程序有问题的几个地方是:
1、参数传递不对,因为你的函数定义时的形参为 以Point 为基类型的指针,而在函数声明和调用中你用的是Point 类型变量;
2、函数的返回值类型和你最后输出的时候的数据格式说明符不符,因此出现了你所说的错误。
修改如下就没问题了
#include <stdio.h>
#include <math.h>
typedef struct {int x; int y;} Point;
int PointDist(Point *);
int main()
{
Point d[2];
printf("Enter the x value of point1:"); scanf("%d",&d[0].x);
printf("Enter the y value of point1:"); scanf("%d",&d[0].y);
printf("Enter the x value of point2:"); scanf("%d",&d[1].x);
printf("Enter the y value of point2:"); scanf("%d",&d[1].y);
printf("The Euclidean distance between two Points is %d\n",PointDist(d)); //把lf改成 d
system("pause");
return 0;
}
int PointDist(Point dot[2]) //实际上如果不修改上面的lf时可以把此处以及函数声明中
//的int改成double
{
int a,b;
a=(dot[0].x-dot[1].x)+(dot[0].y-dot[1].y);
b=a+1;
return b;
}本回答被网友采纳
相似回答