简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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