简体   繁体   English

使用指针和结构计算两点之间的距离C ++,分段错误问题

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

Here I have my code to calculate the distance between the user inputted points, and the calculateDistance function should take in two pointers, I feel like I had it setup right, but when I run the code I get this error: bash: line 12: 25372 Segmentation fault $file.o $args 在这里,我有代码来计算用户输入的点之间的距离,并且calculateDistance函数应该包含两个指针,我觉得我已经正确设置了它,但是当我运行代码时,出现此错误: bash: line 12: 25372 Segmentation fault $file.o $args

Code: 码:

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;
}

One fault is in function calculateDistance . 函数calculateDistance一个错误。 Please change it as 请更改为

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM