Home > Blockchain >  Duplication float values when using structs in a function
Duplication float values when using structs in a function

Time:06-06

I have this program to calculate the midpoint given two points. It takes in the coordinates of two points and return the coordinates of their midpoint.

Somewhere along the way, my program started to output wrong answers. I checked it and found out the faulty part was with the function. I have no idea why this happens.

Attached is my code:

#include <stdio.h>
#include <math.h>

struct line{
    struct point{
        float x;
        float y;
    }point1, point2;
    float *midpoint;
};

float *solveMidpoint(struct line line1){
    float arr[2];
    printf("%f\n", line1.point1.x);
    arr[0] = (line1.point1.x line1.point2.x)/2;
    arr[1] = (line1.point1.y line1.point2.y)/2;
    line1.midpoint = &arr[0];
    return line1.midpoint;
}

int main(void){
    struct line liner;
    printf("Enter x and y for point1: ");
    scanf("%f %f", &(liner.point1.x), &(liner.point1.y));
    printf("Enter x and y for point2: ");
    scanf("%f %f", &(liner.point2.x), &(liner.point2.x));
    printf("Midpoint: %f, %f", *solveMidpoint(liner), *solveMidpoint(liner) 1);
}

When I input two points, it then results to this:

Enter x and y for point1: 1 1
Enter x and y for point2: 0 1
1.000000
1.000000
Midpoint: 1.000000, 2.000000
[Program finished]

The program just printed the float twice. I've made a similar program but the issue doesn't occur in it. What am I doing wrong?

CodePudding user response:

line1.midpoint = &arr[0];

You're bringing out a pointer to a local variable from within your function, when that function ends the array is no longer available. Welcome to undefined behavior territory.

CodePudding user response:

Within the function solveMidpoint you output the same value

printf("%f\n", line1.point1.x);

But returning a pointer to a local array that will not be alive after exiting the function invokes undefined behavior

float *solveMidpoint(struct line line1){
    float arr[2];
    //...
    line1.midpoint = &arr[0];
    return line1.midpoint;
}

And moreover it seems in this statement

printf("Midpoint: %f, %f", *solveMidpoint(liner), *solveMidpoint(liner) 1);

you mean the following arguments

printf("Midpoint: %f, %f", *solveMidpoint(liner), *( solveMidpoint(liner) 1 ));

However there is no reason to declare the pointer within the structure and to return a pointer from the function. You could just return an object of the type float or of a structure type that contains two data members of the type float..

  • Related