C程序中的分段错误(堆芯转储) #包括 #包括 #包括 类型定义结构\u点2D { 双x,y; }点2d,*PPoint2D; 双距离(点2D a、点2D b) { 返回sqrt((a->x-b->x)*(a->x-b->x)+(a->y-b->y)*(a->y-b->y)); } int main() { ppa,b; (a->x)=3.0; (a->y)=2.0; (b->x)=1.0; (b->y)=1.0; printf(“%f”,距离(a,b)); }
我不知道我哪里出错了,我试图得到两个顶点a(3,2)和b(1,1)之间的距离。任何帮助都将不胜感激。C程序中的分段错误(堆芯转储) #包括 #包括 #包括 类型定义结构\u点2D { 双x,y; }点2d,*PPoint2D; 双距离(点2D a、点2D b) { 返回sqrt((a->x-b->x)*(a->x-b->x)+(a->y-b->y)*(a->y-b->y)); } int main() { ppa,b; (a->x)=3.0; (a->y)=2.0; (b->x)=1.0; (b->y)=1.0; printf(“%f”,距离(a,b)); },c,pointers,C,Pointers,我不知道我哪里出错了,我试图得到两个顶点a(3,2)和b(1,1)之间的距离。任何帮助都将不胜感激。#包括 #include<stdio.h> #include<math.h> #include<stdlib.h> typedef struct _Point2D { double x, y; }Point2D, *PPoint2D; double distance(PPoint2D a, PPoint2D b) { return sqrt(
#包括
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
typedef struct _Point2D
{
double x, y;
}Point2D, *PPoint2D;
double distance(PPoint2D a, PPoint2D b)
{
return sqrt((a->x - b->x) * (a->x - b->x) + (a->y - b->y) * (a->y - b->y));
}
int main()
{
PPoint2D a, b;
(a->x) = 3.0;
(a->y) = 2.0;
(b->x) = 1.0;
(b->y) = 1.0;
printf("%f", distance(a, b));
}
#包括
#包括
类型定义结构\u点2D
{
双x,y;
}点2d,*PPoint2D;
双距离(点2D a、点2D b)
{
返回sqrt((a->x-b->x)*(a->x-b->x)+(a->y-b->y)*(a->y-b->y));
}
int main()
{
ppa,b;
a=(PPoint2D)malloc(sizeof(PPoint2D));
b=(PPoint2D)malloc(sizeof(PPoint2D));
(a->x)=3.0;
(a->y)=2.0;
(b->x)=1.0;
(b->y)=1.0;
printf(“%f”,距离(a,b));
}
这解决了我的问题。谢谢大家。指针
a
和b
未初始化,也未指向任何内容。提示:打开编译器警告。它应该提醒您这一点。我建议避免使用PPoint2D
,在需要指针时使用explictPoint2D*
。请注意,即使您必须将指针传递到这些结构,由于函数距离的签名,也要使用explictPoint2D*
,您不必将a
和b
声明为main
中的指针(并动态分配存储它们所需的内存)。只需将它们声明为point2da={3.2,2.0}编码>并传递他们的地址。。。距离(&a,&b).
。以下是代码的警告:(我已经告诉编译器将警告视为错误,您也应该这样做)
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
typedef struct _Point2D
{
double x, y;
}Point2D, *PPoint2D;
double distance(PPoint2D a, PPoint2D b)
{
return sqrt((a->x - b->x)*(a->x - b->x) + (a->y - b->y)*(a->y - b->y));
}
int main()
{
PPoint2D a, b;
a = (PPoint2D)malloc(sizeof(PPoint2D));
b = (PPoint2D)malloc(sizeof(PPoint2D));
(a->x) = 3.0;
(a->y) = 2.0;
(b->x) = 1.0;
(b->y) = 1.0;
printf("%f", distance(a, b));
}