使用指针和结构C 计算两个点之间的距离,分割故障问题

Calculate distance between two points using pointers and structures C++, Segmentation Fault issue

本文关键字:之间 两个 距离 问题 故障 分割 指针 结构 计算      更新时间:2023-10-16

在这里,我有我的代码来计算用户输入点之间的距离,而 calculateDistance函数应采用两个指针,我觉得我已经设置了正确的设置,但是当我运行时代码我得到此错误:bash: line 12: 25372 Segmentation fault $file.o $args

代码:

struct Point{
    float x;
    float y;
};
float calculateDistance(struct Point *p1, struct Point *p2){
    float *fx, *fy;
    *fx = (*p1).x - (*p2).x;
    *fy = (*p1).y - (*p2).y;
    return sqrt((*fx * *fx) + (*fy * *fy));
}
int main()
{
    struct Point *p1, *p2, q, w;
    p1 = &q;
    p2 = &w;
    //float distance;
    cout << "Enter coordinate for p1x: " << endl;
    cin >> (*p1).x;
    cout << "Enter coordinate for p1y: " << endl;
    cin >> (*p1).y;
    cout << "Enter coordinate for p2x: " << endl;
    cin >> (*p2).x;
    cout << "Enter coordinate for p2y: " << endl;
    cin >> (*p2).y;
    //distance = calculateDistance(*p1, *p2);
    cout << "Distance between points: " << calculateDistance(p1, p2) << endl;
    return 0;
}

一个故障在功能calculateDistance中。请更改为

float calculateDistance(struct Point *p1, struct Point *p2){
    float fx, fy;
    fx = (*p1).x - (*p2).x;
    fy = (*p1).y - (*p2).y;
    return sqrt((fx * fx) + (fy * fy));
}